Handling exceptions
In RESTful applications, Flask allows the endpoint function to trigger error handlers that return error messages in JSON format. The following snippets are the error handlers of our ch03
application:
@app.errorhandler(404) def not_found(e): return jsonify(error=str(e)), 404 @app.errorhandler(400) def bad_request(e): return jsonify(error=str(e)), 400 def server_error(e): print(e) return jsonify(error=str(e)), 500 app.register_error_handler(500, server_error)
Error handlers can also return the JSON response through the jsonify()
, make_response()
, or Response
class. As shown in the given error handlers, the implementation is the same with the web-based error handlers except for the jsonify()
method, which serializes the captured error message to the JSON type instead of using render_template()
.
Custom exception classes must include both the HTTP Status Code and error...