有三种情况下我需要处理异常。在
当数据验证引发异常时
当库/模块函数引发异常时(例如数据库连接中止)
当业务逻辑引发异常时,例如500503401403404
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
和所有{json.dumps
和{request.response
对象之前设置一个模板error
主体。在
创意:
^{pr2}$我可以为所有未捕获的、未指定的异常(这会导致500个内部服务器错误)概括为500_internal_server_error_view
。在
在人们看来这是理智和干净的吗?我处理高级别和低级别异常的方法是否正确且具有python特征?在
我将此策略应用于todopyramd,并可以将错误处理封装在一个自定义异常视图中,该视图以前在应用程序中重复多次。在你改进它之前,你有一个好主意。金字塔岩石。在
参考文献
相关问题 更多 >
编程相关推荐