Flask 错误处理的最佳实践是什么?

Ada*_*hes 2 python exception flask

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

中止

import flask
def index(arg):
    return flask.abort("Invalid request", 400)
Run Code Online (Sandbox Code Playgroud)

元组

def index(arg):
    return ("Invalid request", 400)
Run Code Online (Sandbox Code Playgroud)

回复

import flask
def index(arg):
    return flask.Response("Invalid request", 400)
Run Code Online (Sandbox Code Playgroud)

有什么区别以及什么时候会首选?

相关问题

来自Java/Spring,我习惯于定义一个带有与之关联的状态代码的自定义异常,然后每当应用程序抛出该异常时,带有该状态代码的响应就会自动返回给用户(而不必显式捕获它并返回一个响应如上所示)。这可能吗flask?这是我的小尝试

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)
Run Code Online (Sandbox Code Playgroud)

然后使用

try:
    something()
catch FooException as ex:
    return ex.as_http_error()
Run Code Online (Sandbox Code Playgroud)

小智 10

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

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

@app.errorhandler(FooException)
def handle_foo_exception(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读更多相关信息:实现 API 异常