Merge pull request #3260 from LBWright/error-handling
adds api error handling example to documentation
This commit is contained in:
commit
f7f1d9de3d
1 changed files with 26 additions and 0 deletions
|
|
@ -97,3 +97,29 @@ An example template might be this:
|
||||||
<p>What you were looking for is just not there.
|
<p>What you were looking for is just not there.
|
||||||
<p><a href="{{ url_for('index') }}">go somewhere nice</a>
|
<p><a href="{{ url_for('index') }}">go somewhere nice</a>
|
||||||
{% endblock %}
|
{% 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)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue