如何在 Falcon 框架中对任何未处理的异常使用 HTTP 500 进行响应

Ant*_*iev 7 python http falconframework

Falcon框架中是否有办法在资源处理程序中未处理的任何非特定异常上响应 HTTP 500 状态?我试图为异常添加以下处理程序:

api.add_error_handler(Exception, 
                      handler=lambda e, 
                      *_: exec('raise falcon.HTTPInternalServerError("Internal Server Error", "Some error")'))
Run Code Online (Sandbox Code Playgroud)

但这使得无法抛出,例如,falcon.HTTPNotFound它由上面的处理程序处理,我收到 500 而不是 404。

Jav*_*ock 7

对的,这是可能的。您需要定义一个通用错误处理程序,检查异常是否是任何 falcon 错误的实例,如果不是,则引发您的 HTTP_500。

这个例子展示了一种方法。

def generic_error_handler(ex, req, resp, params):
    if not isinstance(ex, HTTPError):
        raise HTTPInternalServerError("Internal Server Error", "Some error")
    else:  # reraise :ex otherwise it will gobble actual HTTPError returned from the application code ref. /sf/answers/4242473231/
        raise ex

app = falcon.API()
app.add_error_handler(Exception, generic_error_handler)
Run Code Online (Sandbox Code Playgroud)