烧瓶错误处理的最佳实践是什么? [英] What is best practice for flask error handling?

查看:32
本文介绍了烧瓶错误处理的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 flask 网络应用程序中向客户端返回 400/500 响应,我已经看到以下约定:

For returning a 400/500 response to clients in a flask webapp, I've seen the following conventions:

import flask
def index(arg):
    return flask.abort("Invalid request", 400)

元组

def index(arg):
    return ("Invalid request", 400)

响应

import flask
def index(arg):
    return flask.Response("Invalid request", 400)

有什么区别?何时会首选?

What are the difference and when would one be preferred?

来自 Java/Spring ,我习惯用状态代码定义与之关联的自定义异常,然后只要应用程序抛出该异常,带有该状态代码的响应就会自动返回给用户(而不是必须明确捕获它并返回如上所示的响应).这可以在 flask 中使用吗?这是我的小尝试

Coming from Java/Spring, I am used to defining a custom exception with a status code associated with it and then anytime the application throws that exception, a response with that status code is automatically returned to the user (instead of having to explicitly catch it and return a response as shown above). Is this possible in flask? This is my little wrapped attempt

from flask import Response

class FooException(Exception):
    """ Binds optional status code and encapsulates returing Response when error is caught """
    def __init__(self, *args, **kwargs):
        code = kwargs.pop('code', 400)
        Exception.__init__(self)
        self.code = code

    def as_http_error(self):
        return Response(str(self), self.code)

然后使用

try:
    something()
catch FooException as ex:
    return ex.as_http_error()

推荐答案

最佳实践是创建您的自定义异常类,然后通过错误处理程序装饰器向Flask应用注册.您可以从业务逻辑中引发自定义异常,然后允许Flask Error Handler处理任何自定义的异常.(类似的方法也可以在Spring中完成.)

The best practice is to create your custom exception classes and then registering with Flask app through error handler decorator. You can raise a custom exception from business logic and then allow the Flask Error Handler to handle any of custom defined exceptions. (Similar way it's done in Spring as well.)

您可以使用如下所示的装饰器并注册自定义异常.

You can use the decorator like below and register your custom exception.

@app.errorhandler(FooException)
def handle_foo_exception(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

您可以在实现API异常中了解更多信息.

You can read more about it here Implementing API Exceptions

这篇关于烧瓶错误处理的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆