Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

523 lines · 17.9 KiB

Last changed by

Merge branch '2.3.x'David Lordbefore adoption7d399e8

History of this file

Take it

The walk stopped after 200 commits: lines older than 93a7f08 point at it.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 1–152why, one step back
1Handling Application Errors
2===========================34Applications fail, servers fail. Sooner or later you will see an exception5in production. Even if your code is 100% correct, you will still see6exceptions from time to time. Why? Because everything else involved will7fail. Here are some situations where perfectly fine code can lead to server8errors:910- the client terminated the request early and the application was still11 reading from the incoming data12- the database server was overloaded and could not handle the query13- a filesystem is full14- a harddrive crashed15- a backend server overloaded16- a programming error in a library you are using17- network connection of the server to another system failed1819And that's just a small sample of issues you could be facing. So how do we20deal with that sort of problem? By default if your application runs in21production mode, and an exception is raised Flask will display a very simple22page for you and log the exception to the :attr:`~flask.Flask.logger`.2324But there is more you can do, and we will cover some better setups to deal25with errors including custom exceptions and 3rd party tools.262728.. _error-logging-tools:2930Error Logging Tools31-------------------3233Sending error mails, even if just for critical ones, can become34overwhelming if enough users are hitting the error and log files are35typically never looked at. This is why we recommend using `Sentry36<https://sentry.io/>`_ for dealing with application errors. It's37available as a source-available project `on GitHub38<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version39<https://sentry.io/signup/>`_ which you can try for free. Sentry40aggregates duplicate errors, captures the full stack trace and local41variables for debugging, and sends you mails based on new errors or42frequency thresholds.4344To use Sentry you need to install the ``sentry-sdk`` client with extra45``flask`` dependencies.4647.. code-block:: text4849 $ pip install sentry-sdk[flask]5051And then add this to your Flask app:5253.. code-block:: python5455 import sentry_sdk56 from sentry_sdk.integrations.flask import FlaskIntegration5758 sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])5960The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you61get from your Sentry installation.6263After installation, failures leading to an Internal Server Error64are automatically reported to Sentry and from there you can65receive error notifications.6667See also:6869- Sentry also supports catching errors from a worker queue70 (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs71 <https://docs.sentry.io/platforms/python/>`__ for more information.72- `Flask-specific documentation <https://docs.sentry.io/platforms/python/guides/flask/>`__737475Error Handlers76--------------7778When an error occurs in Flask, an appropriate `HTTP status code79<https://developer.mozilla.org/en-US/docs/Web/HTTP/Status>`__ will be80returned. 400-499 indicate errors with the client's request data, or81about the data requested. 500-599 indicate errors with the server or82application itself.8384You might want to show custom error pages to the user when an error occurs.85This can be done by registering error handlers.8687An error handler is a function that returns a response when a type of error is88raised, similar to how a view is a function that returns a response when a89request URL is matched. It is passed the instance of the error being handled,90which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.9192The status code of the response will not be set to the handler's code. Make93sure to provide the appropriate HTTP status code when returning a response from94a handler.959697Registering98```````````99100Register handlers by decorating a function with101:meth:`~flask.Flask.errorhandler`. Or use102:meth:`~flask.Flask.register_error_handler` to register the function later.103Remember to set the error code when returning the response.104105.. code-block:: python106107 @app.errorhandler(werkzeug.exceptions.BadRequest)108 def handle_bad_request(e):109 return 'bad request!', 400110111 # or, without the decorator112 app.register_error_handler(400, handle_bad_request)113114:exc:`werkzeug.exceptions.HTTPException` subclasses like115:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable116when registering handlers. (``BadRequest.code == 400``)117118Non-standard HTTP codes cannot be registered by code because they are not known119by Werkzeug. Instead, define a subclass of120:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and121register and raise that exception class.122123.. code-block:: python124125 class InsufficientStorage(werkzeug.exceptions.HTTPException):126 code = 507127 description = 'Not enough storage space.'128129 app.register_error_handler(InsufficientStorage, handle_507)130131 raise InsufficientStorage()132133Handlers can be registered for any exception class, not just134:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status135codes. Handlers can be registered for a specific class, or for all subclasses136of a parent class.137138139Handling140````````141142When building a Flask application you *will* run into exceptions. If some part143of your code breaks while handling a request (and you have no error handlers144registered), a "500 Internal Server Error"145(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.146Similarly, "404 Not Found"147(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.148If a route receives an unallowed request method, a "405 Method Not Allowed"149(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all150subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by151default in Flask.152

Merge pull request #4491 from octopoulpe/patch-1David Lordbefore adoption598afa0

line 153why, one step back
153Flask gives you the ability to raise any HTTP exception registered by

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 154–233why, one step back
154Werkzeug. However, the default HTTP exceptions return simple exception
155pages. You might want to show custom error pages to the user when an error occurs.156This can be done by registering error handlers.157158When Flask catches an exception while handling a request, it is first looked up by code.159If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.160If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a161generic message about their code, while other exceptions are converted to a162generic "500 Internal Server Error".163164For example, if an instance of :exc:`ConnectionRefusedError` is raised,165and a handler is registered for :exc:`ConnectionError` and166:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`167handler is called with the exception instance to generate the response.168169Handlers registered on the blueprint take precedence over those registered170globally on the application, assuming a blueprint is handling the request that171raises the exception. However, the blueprint cannot handle 404 routing errors172because the 404 occurs at the routing level before the blueprint can be173determined.174175176Generic Exception Handlers177``````````````````````````178179It is possible to register error handlers for very generic base classes180such as ``HTTPException`` or even ``Exception``. However, be aware that181these will catch more than you might expect.182183For example, an error handler for ``HTTPException`` might be useful for turning184the default HTML errors pages into JSON. However, this185handler will trigger for things you don't cause directly, such as 404186and 405 errors during routing. Be sure to craft your handler carefully187so you don't lose information about the HTTP error.188189.. code-block:: python190191 from flask import json192 from werkzeug.exceptions import HTTPException193194 @app.errorhandler(HTTPException)195 def handle_exception(e):196 """Return JSON instead of HTML for HTTP errors."""197 # start with the correct headers and status code from the error198 response = e.get_response()199 # replace the body with JSON200 response.data = json.dumps({201 "code": e.code,202 "name": e.name,203 "description": e.description,204 })205 response.content_type = "application/json"206 return response207208An error handler for ``Exception`` might seem useful for changing how209all errors, even unhandled ones, are presented to the user. However,210this is similar to doing ``except Exception:`` in Python, it will211capture *all* otherwise unhandled errors, including all HTTP status212codes.213214In most cases it will be safer to register handlers for more215specific exceptions. Since ``HTTPException`` instances are valid WSGI216responses, you could also pass them through directly.217218.. code-block:: python219220 from werkzeug.exceptions import HTTPException221222 @app.errorhandler(Exception)223 def handle_exception(e):224 # pass through HTTP errors225 if isinstance(e, HTTPException):226 return e227228 # now you're handling non-HTTP exceptions only229 return render_template("500_generic.html", e=e), 500230231Error handlers still respect the exception class hierarchy. If you232register handlers for both ``HTTPException`` and ``Exception``, the233``Exception`` handler will not handle ``HTTPException`` subclasses

Merge branch '2.3.x'David Lordbefore adoption7d399e8

line 234why, one step back
234because the ``HTTPException`` handler is more specific.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 235–490why, one step back
235
236237Unhandled Exceptions238````````````````````239240When there is no error handler registered for an exception, a 500241Internal Server Error will be returned instead. See242:meth:`flask.Flask.handle_exception` for information about this243behavior.244245If there is an error handler registered for ``InternalServerError``,246this will be invoked. As of Flask 1.1.0, this error handler will always247be passed an instance of ``InternalServerError``, not the original248unhandled error.249250The original error is available as ``e.original_exception``.251252An error handler for "500 Internal Server Error" will be passed uncaught253exceptions in addition to explicit 500 errors. In debug mode, a handler254for "500 Internal Server Error" will not be used. Instead, the255interactive debugger will be shown.256257258Custom Error Pages259------------------260261Sometimes when building a Flask application, you might want to raise a262:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that263something is wrong with the request. Fortunately, Flask comes with a handy264:func:`~flask.abort` function that aborts a request with a HTTP error from265werkzeug as desired. It will also provide a plain black and white error page266for you with a basic description, but nothing fancy.267268Depending on the error code it is less or more likely for the user to269actually see such an error.270271Consider the code below, we might have a user profile route, and if the user272fails to pass a username we can raise a "400 Bad Request". If the user passes a273username and we can't find it, we raise a "404 Not Found".274275.. code-block:: python276277 from flask import abort, render_template, request278279 # a username needs to be supplied in the query args280 # a successful request would be like /profile?username=jack281 @app.route("/profile")282 def user_profile():283 username = request.arg.get("username")284 # if a username isn't supplied in the request, return a 400 bad request285 if username is None:286 abort(400)287288 user = get_user(username=username)289 # if a user can't be found by their username, return 404 not found290 if user is None:291 abort(404)292293 return render_template("profile.html", user=user)294295Here is another example implementation for a "404 Page Not Found" exception:296297.. code-block:: python298299 from flask import render_template300301 @app.errorhandler(404)302 def page_not_found(e):303 # note that we set the 404 status explicitly304 return render_template('404.html'), 404305306When using :doc:`/patterns/appfactories`:307308.. code-block:: python309310 from flask import Flask, render_template311312 def page_not_found(e):313 return render_template('404.html'), 404314315 def create_app(config_filename):316 app = Flask(__name__)317 app.register_error_handler(404, page_not_found)318 return app319320An example template might be this:321322.. code-block:: html+jinja323324 {% extends "layout.html" %}325 {% block title %}Page Not Found{% endblock %}326 {% block body %}327 <h1>Page Not Found</h1>328 <p>What you were looking for is just not there.329 <p><a href="{{ url_for('index') }}">go somewhere nice</a>330 {% endblock %}331332333Further Examples334````````````````335336The above examples wouldn't actually be an improvement on the default337exception pages. We can create a custom 500.html template like this:338339.. code-block:: html+jinja340341 {% extends "layout.html" %}342 {% block title %}Internal Server Error{% endblock %}343 {% block body %}344 <h1>Internal Server Error</h1>345 <p>Oops... we seem to have made a mistake, sorry!</p>346 <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>347 {% endblock %}348349It can be implemented by rendering the template on "500 Internal Server Error":350351.. code-block:: python352353 from flask import render_template354355 @app.errorhandler(500)356 def internal_server_error(e):357 # note that we set the 500 status explicitly358 return render_template('500.html'), 500359360When using :doc:`/patterns/appfactories`:361362.. code-block:: python363364 from flask import Flask, render_template365366 def internal_server_error(e):367 return render_template('500.html'), 500368369 def create_app():370 app = Flask(__name__)371 app.register_error_handler(500, internal_server_error)372 return app373374When using :doc:`/blueprints`:375376.. code-block:: python377378 from flask import Blueprint379380 blog = Blueprint('blog', __name__)381382 # as a decorator383 @blog.errorhandler(500)384 def internal_server_error(e):385 return render_template('500.html'), 500386387 # or with register_error_handler388 blog.register_error_handler(500, internal_server_error)389390391Blueprint Error Handlers392------------------------393394In :doc:`/blueprints`, most error handlers will work as expected.395However, there is a caveat concerning handlers for 404 and 405396exceptions. These error handlers are only invoked from an appropriate397``raise`` statement or a call to ``abort`` in another of the blueprint's398view functions; they are not invoked by, e.g., an invalid URL access.399400This is because the blueprint does not "own" a certain URL space, so401the application instance has no way of knowing which blueprint error402handler it should run if given an invalid URL. If you would like to403execute different handling strategies for these errors based on URL404prefixes, they may be defined at the application level using the405``request`` proxy object.406407.. code-block:: python408409 from flask import jsonify, render_template410411 # at the application level412 # not the blueprint level413 @app.errorhandler(404)414 def page_not_found(e):415 # if a request is in our blog URL space416 if request.path.startswith('/blog/'):417 # we return a custom blog 404 page418 return render_template("blog/404.html"), 404419 else:420 # otherwise we return our generic site-wide 404 page421 return render_template("404.html"), 404422423 @app.errorhandler(405)424 def method_not_allowed(e):425 # if a request has the wrong method to our API426 if request.path.startswith('/api/'):427 # we return a json saying so428 return jsonify(message="Method Not Allowed"), 405429 else:430 # otherwise we return a generic site-wide 405 page431 return render_template("405.html"), 405432433434Returning API Errors as JSON435----------------------------436437When building APIs in Flask, some developers realise that the built-in438exceptions are not expressive enough for APIs and that the content type of439:mimetype:`text/html` they are emitting is not very useful for API consumers.440441Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON442responses to API errors. :func:`~flask.abort` is called443with a ``description`` parameter. The error handler will444use that as the JSON error message, and set the status code to 404.445446.. code-block:: python447448 from flask import abort, jsonify449450 @app.errorhandler(404)451 def resource_not_found(e):452 return jsonify(error=str(e)), 404453454 @app.route("/cheese")455 def get_one_cheese():456 resource = get_resource()457458 if resource is None:459 abort(404, description="Resource not found")460461 return jsonify(resource)462463We can also create custom exception classes. For instance, we can464introduce a new custom exception for an API that can take a proper human readable message,465a status code for the error and some optional payload to give more context466for the error.467468This is a simple example:469470.. code-block:: python471472 from flask import jsonify, request473474 class InvalidAPIUsage(Exception):475 status_code = 400476477 def __init__(self, message, status_code=None, payload=None):478 super().__init__()479 self.message = message480 if status_code is not None:481 self.status_code = status_code482 self.payload = payload483484 def to_dict(self):485 rv = dict(self.payload or ())486 rv['message'] = self.message487 return rv488489 @app.errorhandler(InvalidAPIUsage)490 def invalid_api_usage(e):

Merge branch '2.1.x'David Lordbefore adoptiona03719b

line 491why, one step back
491 return jsonify(e.to_dict()), e.status_code

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 492–523why, one step back
492
493 # an API app route for getting user information494 # a correct request might be /api/user?user_id=420495 @app.route("/api/user")496 def user_api(user_id):497 user_id = request.arg.get("user_id")498 if not user_id:499 raise InvalidAPIUsage("No user id provided!")500501 user = get_user(user_id=user_id)502 if not user:503 raise InvalidAPIUsage("No such user!", status_code=404)504505 return jsonify(user.to_dict())506507A view can now raise that exception with an error message. Additionally508some extra payload can be provided as a dictionary through the `payload`509parameter.510511512Logging513-------514515See :doc:`/logging` for information about how to log exceptions, such as516by emailing them to admins.517518519Debugging520---------521522See :doc:`/debugging` for information about how to debug errors in523development and production.