如何设置 pgerror 引发 psycopg2 ProgrammingError? [英] How to raise a psycopg2 ProgrammingError with pgerror set?

查看:69
本文介绍了如何设置 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆