如何设置 pgerror 引发 psycopg2 ProgrammingError?

编程入门 行业动态 更新时间:2024-10-24 12:26:48
本文介绍了如何设置 pgerror 引发 psycopg2 ProgrammingError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 try except 块,我在其中执行了一条语句,但它可能会引发 psycopg2 ProgrammingError.我已将其设置为可以很好地处理错误,但我发现很难模拟.我需要能够设置 ProgrammingError 的 pgerror 属性,但它是一个只读属性.

>>>e = 编程错误()>>>e.pgerror = '一个错误'回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中AttributeError: 只读属性

我也尝试在创建错误时设置 pgerror 值

>>>e = ProgrammingError(pgerror='一个错误')回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中类型错误:ProgrammingError() 不接受关键字参数

还有其他方法可以设置值吗?

解决方案

我发现我可以使用 dunder setstate 来设置 pgerror 的值

e = ProgrammingError()e.__setstate__({"pgerror": "一个错误"})提高e

然后当错误被捕获时,它会将 pgerror 属性设置为 an error

I have a try except block where I execute a statement but there is a chance that it may raise a psycopg2 ProgrammingError. I have it set up to handle the error just fine but I am finding it difficult to mock. I need to be able to set the pgerror property of the ProgrammingError but it is a read only property.

>>> e = ProgrammingError() >>> e.pgerror = 'an error' Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: readonly attribute

I have also tried to set the pgerror value when I create the error

>>> e = ProgrammingError(pgerror='an error') Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: ProgrammingError() takes no keyword arguments

Is there another way I could set the value?

解决方案

I found that I could use the dunder setstate to set the value of pgerror

e = ProgrammingError() e.__setstate__({"pgerror": "an eror"}) raise e

Then when the error is caught it will have the pgerror property set to an error

更多推荐

如何设置 pgerror 引发 psycopg2 ProgrammingError?

本文发布于:2023-10-16 12:14:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何设置   pgerror   ProgrammingError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!