[英]What's the most pythonic way to get name of the field when an exception related to IntegrityError is thrown?
I'm developing an API with DRF and I want to generate and return proper custom error messages when an exception related to IntegrityError is thrown. 我正在使用DRF开发API,当引发与IntegrityError相关的异常时,我想生成并返回正确的自定义错误消息。
To do this, I've implemented a custom exception handler. 为此,我实现了一个自定义的异常处理程序。 Inside the custom exception handler, I want to get the name of the field that causes the error from the Exception instance and then I'll generate and return proper message in the response.
在自定义异常处理程序中,我想从Exception实例中获取导致错误的字段的名称,然后在响应中生成并返回正确的消息。
Currently, I can do this by parsing the message attribute of the Exception instance but I'm not sure this is the best possible solution. 当前,我可以通过解析Exception实例的message属性来做到这一点,但是我不确定这是否是最好的解决方案。
So, is there any pythonic way to get the name of the field from the Exception instance when an exception related to IntegrityError is thrown? 因此,当引发与IntegrityError相关的异常时,是否有任何pythonic方式可从Exception实例获取字段名称?
Thanks! 谢谢!
According to source it seems IntergityError is no more than an Exception so the only way is to parsing exception.message
or exception.args
. 根据消息来源 ,IntergityError似乎不只是一个Exception,所以唯一的方法是解析
exception.message
或exception.args
。
You always can check what gives you print(dir(exception))
but I'm pretty sure only message
and args
will be helpful. 您始终可以检查为您提供了
print(dir(exception))
但是我敢肯定,只有message
和args
会有所帮助。
IMHO "parsing the message" is perfectly pythonic: simple, readable, you can do the same/similar solution in any other similar situation. 恕我直言,“解析消息”完全是Python风格的:简单,易读,您可以在任何其他类似情况下执行相同/相似的解决方案。 I've seen something like this before:
我以前看过这样的东西:
# in a custom Serializer's create() method
try:
return super().create(validated_data)
except IntegrityError as e:
raise APIException(detail=e.args[0].split('DETAIL: ')[1])
It simple, it works and getting the extra data in any other way will likely involve something significantly more complicated. 它简单易行,并且以任何其他方式获取额外数据可能会涉及到非常复杂的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.