【发布时间】:2014-04-11 05:37:53
【问题描述】:
我需要处理异常的三种情况。
当数据验证引发异常时
当库/模块函数引发异常时(例如数据库连接中止)
当业务逻辑引发 500、503、401、403 和 404 等异常时
def library_func():
try:
...
except HTTPException:
raise TwitterServiceException("Twitter is down!")
@view_config(route_name="home", renderer="json")
@validator
@authorization
def home_view(request):
try:
tweets = library_func()
return {"tweets": tweets}
except TwitterServiceException as e:
LOG.critical(e.msg)
raise ParnterServcieError(e.msg) # this is probably a 503 error
def validator(args):
# I will show the high level of this decorator
try:
decode input as JSON
verify data format
except ValueError as err:
error = {'error': "Missing required parameters."}
except json.JSONDecodeError as err:
error = {'error': "Failed to decode the incoming JSON payload."}
if error is not None:
return HTTPBadRequest(body=json.dumps(error),
content_type='application/json')
def authorization(args):
# very similar to validator except it performs authorization and if failed
# 401 is raised with some helpful message.
文档建议Custom Exception Views。在我上面的 PoC 中,我将 ParnterServcieError 并列在一起。我什至可以使用自定义异常来概括HTTPBadRequest 和所有praymid.httpexceptions,这样我就不再需要重复json.dumps 和content_type。我可以在返回 request.response 对象之前设置一个样板文件 error 正文。
想法:
@view_config(context=ParnterServcieError)
def 503_service_error_view(e, request):
request.response.status = 503
request.response.json_body = {"error": e.msg}
return request.response
我可以为所有未捕获的、未指定的异常(导致 500 内部服务器错误)概括一个称为 500_internal_server_error_view。
这在人们看来是理智和干净的吗?我处理高低级别异常的方式是否正确和 Pythonic?
【问题讨论】:
标签: python exception web-applications pyramid