Skip to content
Myr

reword api error section

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 7bc965f · Browse files · 1 file+14 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+14 added−15 removed

  • other:+14 added−15 removed

1 file+14 added−15 removed

modified:docs/patterns/errorpages.rst+14 added-15 removed
97 unmodified lines
98 <p><a href="{{ url_for('index') }}">go somewhere nice</a>99 {% endblock %}100101102Handling API Errors with Abort103------------------------------102Returning API errors as JSON103----------------------------104105When using Flask for web APIs, handling errors is as simple as the previous examples but with minor changes.105When using Flask for web APIs, you can use the same techniques as above106to return JSON responses to API errors. :func:`~flask.abort` is called107with a ``description`` parameter. The :meth:`~flask.errorhandler` will108use that as the JSON error message, and set the status code to 404.109107Register the error handler::110.. code-block:: python111109 from flask import jsonify112 from flask import abort, jsonify113114 @app.errorhandler(404)115 def resource_not_found(e):113 # if passing in an Exception object directly, you may need to convert it to a string116 return jsonify(error=str(e)), 404117116To use this error handler::117118 @app.route('/cheese', methods=['GET'])118 @app.route("/cheese")119 def get_one_cheese():120 # logic to find your resource121 if (resource is None):122 abort(404, 'Resource not found')123 else:124 return jsonify(resource=resource)120 resource = get_resource()121126In the above example, the error handler is invoked with the second argument passed to it. It returns the json message with the response.122 if resource is None:123 abort(404, description="Resource not found")124125 return jsonify(resource)