【发布时间】:2020-07-30 23:14:59
【问题描述】:
这是我在 django 项目中的异常处理示例:
def boxinfo(request, url: str):
box = get_box(url)
try:
box.connect()
except requests.exceptions.ConnectionError as e:
context = {'error_message': 'Could not connect to your box because the host is unknown.'}
return render(request, 'box/error.html', context)
except requests.exceptions.RequestException as e:
context = {'error_message': 'Could not connect to your box because of an unknown error.'}
return render(request, 'box/error.html', context)
- 现在只有两个异常,但是对于几个请求异常应该会更多。但是视图方法已经被这个膨胀了。有没有办法将异常处理转发到单独的错误方法?
- 还有一个问题,我需要在这里为每个例外调用渲染消息,我想避免这种情况。
- 这里我也重复每个除了“无法连接到你的盒子因为”,当出现任何异常时应该设置一次。
我可以这样解决:
try:
box.connect()
except Exception as e:
return error_handling(request, e)
-
def error_handling(request, e):
if type(e).__name__ == requests.exceptions.ConnectionError.__name__:
context = {'error_message': 'Could not connect to your box because the host is unknown.'}
elif type(e).__name__ == requests.exceptions.RequestException.__name__:
context = {'error_message': 'Could not connect to your box because of an unknown error.'}
else:
context = {'error_message': 'There was an unkown error, sorry.'}
return render(request, 'box/error.html', context)
然后我当然可以改进错误消息的事情。但总的来说,它是用if/else 处理异常的pythonic 方式吗?例如,如果抛出ConnectionError,我无法在此处捕获RequestException,因此我需要捕获每个请求错误,这看起来更像是一个丑陋的摆弄......
【问题讨论】:
-
好吧,这可能是stackoverflow.com/questions/38084360/…的副本,建议在
if type(e).__name__ == 'ReadError'的函数中处理,这真的是pythonic/django的方式吗? -
这不是pythonic。通常使用
__dunder__方法是最后的手段/解决方法,特别是检查类名非常hacky。试试usingisinstanceinstead