Skip to main content
 首页 » 编程设计

python之Flask-Restful 中输出异常信息

2025年05月04日38虾米姐

在 Flask-Restful 中,可以在引发某些特定异常时定义特定的静态消息:

errors = { 
           'SomeException': { 
            'message': 'Some custom error message', 
            'status': 500, 
        } 
} 
 
api_bp = Blueprint('my_bp', __name__) 
api = Api(api_bp, errors=errors) 

问题是我的 SomeException 包含我也想在响应中返回的数据。有办法吗?使用纯 Flask,我可以创建一个包含所有需要的逻辑的函数,并用 errorhandler 装饰器装饰它。

但是我如何使用 Flask-Restful 做到这一点呢?

请您参考如下方法:

您可以在 abort() 调用中定义错误消息。

if something_is_wrong: 
    custom_message = 'Here is my custom error' 
    abort(400, message='There is an error: ' + custom_message) 

这将中止脚本并返回 HTTP 状态 400 响应,正文中包含以下内容:

{"message":"There is an error: Here is my custom error"}