有关Pyramid视图异常处理的建议

时间:2014-04-11 05:37:54

标签: python exception web-applications pyramid

我需要处理异常时有三种情况。

当数据验证引发异常时

当库/模块函数引发异常(例如数据库连接中止)时

当业务逻辑引发诸如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.dumpscontent_type。在我返回error对象之前,我可以设置样板request.response

点子:

@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的方式是什么?

1 个答案:

答案 0 :(得分:0)

我将此策略应用于ToDoPyramid,并且可以将错误处理封装在之前在应用程序中重复多次的单个自定义异常视图中。直到你甚至可以改进它,你有一个好主意。金字塔岩石。

参考