金字塔视图异常处理建议

2024-04-20 06:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当数据验证引发异常时

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

当业务逻辑引发异常时,例如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特征?在


Tags: viewjsonhomeisdefaslibraryerror
1条回答
网友
1楼 · 发布于 2024-04-20 06:17:04

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

参考文献

相关问题 更多 >