- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我的一些 api View 是这样的:
try:
do_stuff()
except KeyError as exc:
logger.log(exc)
raise APIException("No good")
理想情况下,我不想像这样登录每一段代码,而是使用捕获 APIException 的通用异常处理程序,因此我将代码更改为:
try:
do_stuff()
except KeyError as exc:
raise APIException(exc)
def exception_handler(...):
logger.log(exc) # I want to log the KeyError...
return Response({"message": "try again sam"}, status_code=400)
我的问题是处理程序中的 exc 不是 keyerror 而是 apiexception,我能以某种方式从 sys.exc_info 或堆栈跟踪中获取 KeyError 吗?
最佳答案
好的做法是引发您自己的异常(此处为 APIException
)并附加原始异常。
可以看看six.raise_from (如果你想要一个 Python 2/3 兼容的解决方案):
Raise an exception from a context. On Python 3, this is equivalent to
raise exc_value from exc_value_from
. On Python 2, which does not support exception chaining, it is equivalent to raise exc_value.
您还可以创建自己的异常类来进行链接。
class APIException(Exception):
def __init__(self, msg, exc_from=None):
self.exc_from = exc_from
if exc_from:
msg += ': raise from {0}'.format(str(exc_from))
super(APIException, self).__init__(self, msg)
# demo
def do_stuff():
raise KeyError('bad key')
def main():
try:
do_stuff()
except KeyError as exc:
raise APIException('error in main', exc)
try:
main()
except APIException as exc:
print(str(exc))
当然,您可以记录原始消息,而不是打印/记录 APIException 错误消息:
try:
main()
except APIException as exc:
print(str(exc.exc_from))
编辑:对异常使用类层次结构
但是,如果 do_stuff()
是您的 API 的一部分,那么最好在该函数内进行异常处理并抛出您自己的可以继承 APIException
的异常.
class APIException(Exception):
pass
class BadStuffError(APIException):
pass
def do_stuff():
try:
# ...
raise KeyError('bad key')
except KeyError as exc:
raise BadStuffError('bad stuff: ' + exc.args[0])
def main():
do_stuff()
try:
main()
except APIException as exc:
print(str(exc))
IMO,这个解决方案是最好的。
关于Python 在广泛的处理程序中捕获先前的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175875/
我的应用将 SceneKit 内容的“页面”与图像和文本交替。当我从图像页面前进到新的 SceneKit 页面时,前一个 SceneKit 页面中的内容会短暂显示,然后被新内容替换。时髦。 我只使用一
我正在尝试处理(在 C# 中)包含一些数字数据的大型数据文件。给定一个整数数组,如何对其进行拆分/分组,以便如果下一个 n(两个或更多)是负数,则前一个 n 元素被分组。例如,在下面的数组中,应该使用
刚接触promises,研究过。所以我的代码和我的理解: sql.connect(config).then(function(connection) { return connection.req
目前我在 if (roobaf) block 中有一些代码,这取决于 foo 和 bar 是否为假。我可以在 block 内再次检查这些条件,但感觉像是不必要的代码重复。 if (foo) {
我是一名优秀的程序员,十分优秀!