Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 72 ยท Routing and Views

Error Handling and Custom Error Pages

Learn to raise HTTP errors with abort, write custom 404 and 500 pages with errorhandler, return JSON errors for APIs, and handle your own exception classes.

Things go wrong on the web all the time. A visitor mistypes a URL, asks for a record that was deleted, submits a broken form, or hits a bug you have not found yet. What matters is how your app responds: with the right status code, a message that helps, and a page that still looks like your site.

Flask has a small, consistent model for this. You raise an error (usually with abort()), and Flask looks for a matching error handler that turns the error into a response. In this lesson you'll raise HTTP errors, replace the default pages, return JSON errors for API clients, and map your own exception classes to responses.

Raising errors with abort

abort(404) stops the current view immediately, no matter how deep in your code you are. It works by raising an HTTPException subclass (NotFound for 404, Forbidden for 403, and so on) from Werkzeug. You can add your own explanation with description.

Even without any setup, Flask answers unknown URLs with a 404 and wrong methods with a 405. These are the same exceptions, raised by the router.

Python abort and the default error pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The default error body is a small HTML page produced by Werkzeug. The 405 response also carries an Allow header listing the methods the URL accepts, which is part of the HTTP rules. Visitors get a bare-bones page that does not look like your site, so you will want to replace it.

Custom error pages with errorhandler

Register a function with @app.errorhandler(code). It receives the exception and returns a normal response, including a status code. Remember to include the status code yourself: if you return only a string, Flask would answer 200 and search engines would index your "not found" page as real content.

flowchart TD
    A["view raises HTTPException<br/>(abort or router)"] --> B{"handler registered<br/>for this code?"}
    B -->|yes| C["call handler(error)"]
    B -->|no| D{"handler for a parent<br/>class, such as HTTPException?"}
    D -->|yes| C
    D -->|no| E["Werkzeug default page"]
    C --> F["handler's response is sent"]

Flask picks the most specific handler: the code first, then the exception's class hierarchy.

Python Custom 404 and 500 pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real project the pages would come from template files (render_template("errors/404.html")) so they share the site layout from Template Inheritance and Includes.

The 500 handler also catches unhandled exceptions from your code, not only abort(500). In that case error.original_exception holds the real exception. Flask logs the traceback first, then calls your handler. While app.debug or app.testing is on, unhandled exceptions are not turned into 500 pages: you see the debugger or the exception itself, which is what you want during development.

Never show the exception text or a traceback to visitors in production. It leaks implementation details. Log it, show a friendly message.

JSON errors for APIs

A browser expects an HTML page, but a client that called /api/books/99 expects JSON. A single handler for the base class HTTPException can cover all the codes at once, and you can choose the format by looking at the request path or the Accept header. Handlers registered for a specific code, such as 404, win over the base-class handler.

Python One handler for every HTTP error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the router's own 404 and 405 errors went through the same handler, so the /api/ paths get consistent JSON even for URLs that do not exist. The full API error format is worked out in Building JSON APIs.

Your own exception classes

Big applications raise domain errors deep inside service code: OutOfStock, PaymentDeclined, PermissionDenied. You can register handlers for these classes too, which keeps views free of try/except blocks. The decorator @app.errorhandler(SomeException) and the method app.register_error_handler(SomeException, func) do the same thing; the method form is handy for functions defined elsewhere and for blueprints.

Python Handling custom exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When more than one handler could match, Flask walks the exception's class hierarchy and uses the most specific one. A handler registered for Exception would catch everything else, but be careful: it also catches HTTPException subclasses unless you register a more specific handler for those first, so write isinstance(error, HTTPException) checks (or register HTTPException as well).

Good practice

  • Use the right status: 400 for bad input, 401 when login is needed, 403 when it is forbidden, 404 when it does not exist, 409 for conflicts, 422 for validation failures, 500 for your bugs.
  • Always return the status code from error handlers.
  • Keep error pages light: they should work even when the database is down, so avoid queries in a 500 template.
  • Log unexpected failures (Logging and Debugging); user mistakes need no alarm.
  • With blueprints, a handler registered on a blueprint only covers that blueprint's views, except 404, which is raised before a blueprint is chosen and must be registered on the app.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does abort(404) do inside a view?

    abort raises NotFound (an HTTPException), which Flask turns into a response through an error handler or the default page.
  2. 2. Your 404 handler is return render_template_string(PAGE). What status code does the client get?

    A handler's return value is a normal response. Without an explicit status the default 200 is used, so return (html, 404).
  3. 3. Which registration catches every HTTP error, including the router's own 404 and 405?

    All Werkzeug HTTP errors subclass HTTPException, so a handler for that class sees them all unless a more specific one exists.
  4. 4. How do you make OutOfStock (a plain Python exception) produce a 409 JSON response?

    Error handlers work for any exception class, not just HTTP errors.

Summary

  • abort(code) raises an HTTPException; the router raises 404 and 405 the same way.
  • @app.errorhandler(code_or_class) and app.register_error_handler() map errors to responses. Always include the status code in the handler's return value.
  • The most specific handler wins: a status code, then the exception class hierarchy.
  • A handler for HTTPException can return JSON for /api/ paths and HTML elsewhere.
  • Custom exception classes keep business rules out of views.
  • Unhandled exceptions become 500 responses in production; never expose tracebacks to visitors.

Next: Jinja Templates Basics, turning data into HTML.