Global error handler for any exception

前端 未结 6 1632
旧时难觅i
旧时难觅i 2020-12-04 18:07

Is there a way to add a global catch-all error handler in which I can change the response to a generic JSON response?

I can\'t use the got_request_exception

6条回答
  •  再見小時候
    2020-12-04 18:15

    Based on Plain (non-HTML) error pages in REST api

    I wanted to return json without changing any of my code at all, so I just added the following on the top of my code

    @app.errorhandler(500)
    def error_500(exception):
        return jsonify({"error": str(exception)}), 500, {'Content-Type': 'application/json'}
    
    @app.errorhandler(400)
    def error_400(exception):
        return jsonify({"error": str(exception)}), 400, {'Content-Type': 'application/json'}
    

提交回复
热议问题