Merge pull request #3260 from LBWright/error-handling

adds api error handling example to documentation
This commit is contained in:
David Lord 2019-06-12 11:07:04 -07:00 committed by GitHub
commit f7f1d9de3d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -97,3 +97,29 @@ An example template might be this:
<p>What you were looking for is just not there.
<p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}
Returning API errors as JSON
----------------------------
When using Flask for web APIs, you can use the same techniques as above
to return JSON responses to API errors. :func:`~flask.abort` is called
with a ``description`` parameter. The :meth:`~flask.errorhandler` will
use that as the JSON error message, and set the status code to 404.
.. code-block:: python
from flask import abort, jsonify
@app.errorhandler(404)
def resource_not_found(e):
return jsonify(error=str(e)), 404
@app.route("/cheese")
def get_one_cheese():
resource = get_resource()
if resource is None:
abort(404, description="Resource not found")
return jsonify(resource)