Handling Application Errors

Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors:

  • the client terminated the request early and the application was still reading from the incoming data

  • the database server was overloaded and could not handle the query

  • a filesystem is full

  • a harddrive crashed

  • a backend server overloaded

  • a programming error in a library you are using

  • network connection of the server to another system failed

And that’s just a small sample of issues you could be facing. So how do we deal with that sort of problem? By default if your application runs in production mode, and an exception is raised Flask will display a very simple page for you and log the exception to the logger.

But there is more you can do, and we will cover some better setups to deal with errors including custom exceptions and 3rd party tools.

Error Logging Tools

Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s available as a source-available project on GitHub and is also available as a hosted version which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds.

To use Sentry you need to install the sentry-sdk client with extra flask dependencies.

  1. $ pip install sentry-sdk[flask]

And then add this to your Flask app:

  1. import sentry_sdk
  2. from sentry_sdk.integrations.flask import FlaskIntegration
  3. sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])

The YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your Sentry installation.

After installation, failures leading to an Internal Server Error are automatically reported to Sentry and from there you can receive error notifications.

See also:

Error Handlers

When an error occurs in Flask, an appropriate HTTP status code will be returned. 400-499 indicate errors with the client’s request data, or about the data requested. 500-599 indicate errors with the server or application itself.

You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.

An error handler is a function that returns a response when a type of error is raised, similar to how a view is a function that returns a response when a request URL is matched. It is passed the instance of the error being handled, which is most likely a HTTPException.

The status code of the response will not be set to the handler’s code. Make sure to provide the appropriate HTTP status code when returning a response from a handler.

Registering

Register handlers by decorating a function with errorhandler(). Or use register_error_handler() to register the function later. Remember to set the error code when returning the response.

  1. @app.errorhandler(werkzeug.exceptions.BadRequest)
  2. def handle_bad_request(e):
  3. return 'bad request!', 400
  4. # or, without the decorator
  5. app.register_error_handler(400, handle_bad_request)

werkzeug.exceptions.HTTPException subclasses like BadRequest and their HTTP codes are interchangeable when registering handlers. (BadRequest.code == 400)

Non-standard HTTP codes cannot be registered by code because they are not known by Werkzeug. Instead, define a subclass of HTTPException with the appropriate code and register and raise that exception class.

  1. class InsufficientStorage(werkzeug.exceptions.HTTPException):
  2. code = 507
  3. description = 'Not enough storage space.'
  4. app.register_error_handler(InsufficientStorage, handle_507)
  5. raise InsufficientStorage()

Handlers can be registered for any exception class, not just HTTPException subclasses or HTTP status codes. Handlers can be registered for a specific class, or for all subclasses of a parent class.

Handling

When building a Flask application you will run into exceptions. If some part of your code breaks while handling a request (and you have no error handlers registered), a “500 Internal Server Error” (InternalServerError) will be returned by default. Similarly, “404 Not Found” (NotFound) error will occur if a request is sent to an unregistered route. If a route receives an unallowed request method, a “405 Method Not Allowed” (MethodNotAllowed) will be raised. These are all subclasses of HTTPException and are provided by default in Flask.

Flask gives you the ability to raise any HTTP exception registered by Werkzeug. However, the default HTTP exceptions return simple exception pages. You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.

When Flask catches an exception while handling a request, it is first looked up by code. If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen. If no handler is registered, HTTPException subclasses show a generic message about their code, while other exceptions are converted to a generic “500 Internal Server Error”.

For example, if an instance of ConnectionRefusedError is raised, and a handler is registered for ConnectionError and ConnectionRefusedError, the more specific ConnectionRefusedError handler is called with the exception instance to generate the response.

Handlers registered on the blueprint take precedence over those registered globally on the application, assuming a blueprint is handling the request that raises the exception. However, the blueprint cannot handle 404 routing errors because the 404 occurs at the routing level before the blueprint can be determined.

Generic Exception Handlers

It is possible to register error handlers for very generic base classes such as HTTPException or even Exception. However, be aware that these will catch more than you might expect.

For example, an error handler for HTTPException might be useful for turning the default HTML errors pages into JSON. However, this handler will trigger for things you don’t cause directly, such as 404 and 405 errors during routing. Be sure to craft your handler carefully so you don’t lose information about the HTTP error.

  1. from flask import json
  2. from werkzeug.exceptions import HTTPException
  3. @app.errorhandler(HTTPException)
  4. def handle_exception(e):
  5. """Return JSON instead of HTML for HTTP errors."""
  6. # start with the correct headers and status code from the error
  7. response = e.get_response()
  8. # replace the body with JSON
  9. response.data = json.dumps({
  10. "code": e.code,
  11. "name": e.name,
  12. "description": e.description,
  13. })
  14. response.content_type = "application/json"
  15. return response

An error handler for Exception might seem useful for changing how all errors, even unhandled ones, are presented to the user. However, this is similar to doing except Exception: in Python, it will capture all otherwise unhandled errors, including all HTTP status codes.

In most cases it will be safer to register handlers for more specific exceptions. Since HTTPException instances are valid WSGI responses, you could also pass them through directly.

  1. from werkzeug.exceptions import HTTPException
  2. @app.errorhandler(Exception)
  3. def handle_exception(e):
  4. # pass through HTTP errors
  5. if isinstance(e, HTTPException):
  6. return e
  7. # now you're handling non-HTTP exceptions only
  8. return render_template("500_generic.html", e=e), 500

Error handlers still respect the exception class hierarchy. If you register handlers for both HTTPException and Exception, the Exception handler will not handle HTTPException subclasses because the HTTPException handler is more specific.

Unhandled Exceptions

When there is no error handler registered for an exception, a 500 Internal Server Error will be returned instead. See flask.Flask.handle_exception() for information about this behavior.

If there is an error handler registered for InternalServerError, this will be invoked. As of Flask 1.1.0, this error handler will always be passed an instance of InternalServerError, not the original unhandled error.

The original error is available as e.original_exception.

An error handler for “500 Internal Server Error” will be passed uncaught exceptions in addition to explicit 500 errors. In debug mode, a handler for “500 Internal Server Error” will not be used. Instead, the interactive debugger will be shown.

Custom Error Pages

Sometimes when building a Flask application, you might want to raise a HTTPException to signal to the user that something is wrong with the request. Fortunately, Flask comes with a handy abort() function that aborts a request with a HTTP error from werkzeug as desired. It will also provide a plain black and white error page for you with a basic description, but nothing fancy.

Depending on the error code it is less or more likely for the user to actually see such an error.

Consider the code below, we might have a user profile route, and if the user fails to pass a username we can raise a “400 Bad Request”. If the user passes a username and we can’t find it, we raise a “404 Not Found”.

  1. from flask import abort, render_template, request
  2. # a username needs to be supplied in the query args
  3. # a successful request would be like /profile?username=jack
  4. @app.route("/profile")
  5. def user_profile():
  6. username = request.arg.get("username")
  7. # if a username isn't supplied in the request, return a 400 bad request
  8. if username is None:
  9. abort(400)
  10. user = get_user(username=username)
  11. # if a user can't be found by their username, return 404 not found
  12. if user is None:
  13. abort(404)
  14. return render_template("profile.html", user=user)

Here is another example implementation for a “404 Page Not Found” exception:

  1. from flask import render_template
  2. @app.errorhandler(404)
  3. def page_not_found(e):
  4. # note that we set the 404 status explicitly
  5. return render_template('404.html'), 404

When using Application Factories:

  1. from flask import Flask, render_template
  2. def page_not_found(e):
  3. return render_template('404.html'), 404
  4. def create_app(config_filename):
  5. app = Flask(__name__)
  6. app.register_error_handler(404, page_not_found)
  7. return app

An example template might be this:

  1. {% extends "layout.html" %}
  2. {% block title %}Page Not Found{% endblock %}
  3. {% block body %}
  4. <h1>Page Not Found</h1>
  5. <p>What you were looking for is just not there.
  6. <p><a href="{{ url_for('index') }}">go somewhere nice</a>
  7. {% endblock %}

Further Examples

The above examples wouldn’t actually be an improvement on the default exception pages. We can create a custom 500.html template like this:

  1. {% extends "layout.html" %}
  2. {% block title %}Internal Server Error{% endblock %}
  3. {% block body %}
  4. <h1>Internal Server Error</h1>
  5. <p>Oops... we seem to have made a mistake, sorry!</p>
  6. <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>
  7. {% endblock %}

It can be implemented by rendering the template on “500 Internal Server Error”:

  1. from flask import render_template
  2. @app.errorhandler(500)
  3. def internal_server_error(e):
  4. # note that we set the 500 status explicitly
  5. return render_template('500.html'), 500

When using Application Factories:

  1. from flask import Flask, render_template
  2. def internal_server_error(e):
  3. return render_template('500.html'), 500
  4. def create_app():
  5. app = Flask(__name__)
  6. app.register_error_handler(500, internal_server_error)
  7. return app

When using Modular Applications with Blueprints:

  1. from flask import Blueprint
  2. blog = Blueprint('blog', __name__)
  3. # as a decorator
  4. @blog.errorhandler(500)
  5. def internal_server_error(e):
  6. return render_template('500.html'), 500
  7. # or with register_error_handler
  8. blog.register_error_handler(500, internal_server_error)

Blueprint Error Handlers

In Modular Applications with Blueprints, most error handlers will work as expected. However, there is a caveat concerning handlers for 404 and 405 exceptions. These error handlers are only invoked from an appropriate raise statement or a call to abort in another of the blueprint’s view functions; they are not invoked by, e.g., an invalid URL access.

This is because the blueprint does not “own” a certain URL space, so the application instance has no way of knowing which blueprint error handler it should run if given an invalid URL. If you would like to execute different handling strategies for these errors based on URL prefixes, they may be defined at the application level using the request proxy object.

  1. from flask import jsonify, render_template
  2. # at the application level
  3. # not the blueprint level
  4. @app.errorhandler(404)
  5. def page_not_found(e):
  6. # if a request is in our blog URL space
  7. if request.path.startswith('/blog/'):
  8. # we return a custom blog 404 page
  9. return render_template("blog/404.html"), 404
  10. else:
  11. # otherwise we return our generic site-wide 404 page
  12. return render_template("404.html"), 404
  13. @app.errorhandler(405)
  14. def method_not_allowed(e):
  15. # if a request has the wrong method to our API
  16. if request.path.startswith('/api/'):
  17. # we return a json saying so
  18. return jsonify(message="Method Not Allowed"), 405
  19. else:
  20. # otherwise we return a generic site-wide 405 page
  21. return render_template("405.html"), 405

Returning API Errors as JSON

When building APIs in Flask, some developers realise that the built-in exceptions are not expressive enough for APIs and that the content type of text/html they are emitting is not very useful for API consumers.

Using the same techniques as above and jsonify() we can return JSON responses to API errors. abort() is called with a description parameter. The error handler will use that as the JSON error message, and set the status code to 404.

  1. from flask import abort, jsonify
  2. @app.errorhandler(404)
  3. def resource_not_found(e):
  4. return jsonify(error=str(e)), 404
  5. @app.route("/cheese")
  6. def get_one_cheese():
  7. resource = get_resource()
  8. if resource is None:
  9. abort(404, description="Resource not found")
  10. return jsonify(resource)

We can also create custom exception classes. For instance, we can introduce a new custom exception for an API that can take a proper human readable message, a status code for the error and some optional payload to give more context for the error.

This is a simple example:

  1. from flask import jsonify, request
  2. class InvalidAPIUsage(Exception):
  3. status_code = 400
  4. def __init__(self, message, status_code=None, payload=None):
  5. super().__init__()
  6. self.message = message
  7. if status_code is not None:
  8. self.status_code = status_code
  9. self.payload = payload
  10. def to_dict(self):
  11. rv = dict(self.payload or ())
  12. rv['message'] = self.message
  13. return rv
  14. @app.errorhandler(InvalidAPIUsage)
  15. def invalid_api_usage(e):
  16. return jsonify(e.to_dict()), e.status_code
  17. # an API app route for getting user information
  18. # a correct request might be /api/user?user_id=420
  19. @app.route("/api/user")
  20. def user_api(user_id):
  21. user_id = request.arg.get("user_id")
  22. if not user_id:
  23. raise InvalidAPIUsage("No user id provided!")
  24. user = get_user(user_id=user_id)
  25. if not user:
  26. raise InvalidAPIUsage("No such user!", status_code=404)
  27. return jsonify(user.to_dict())

A view can now raise that exception with an error message. Additionally some extra payload can be provided as a dictionary through the payload parameter.

Logging

See Logging for information about how to log exceptions, such as by emailing them to admins.

Debugging

See Debugging Application Errors for information about how to debug errors in development and production.