| 1 |
Exceptions and exception handling |
| 2 |
================================= |
| 3 |
|
| 4 |
Litestar defines a base exception called :class:`LitestarException <litestar.exceptions.LitestarException>` which serves |
| 5 |
as a base class for all other exceptions, see :mod:`API Reference <litestar.exceptions>`. |
| 6 |
|
| 7 |
In general, Litestar has two scenarios for exception handling: |
| 8 |
|
| 9 |
- Exceptions that are raised during application configuration, startup, and initialization, which are handled like regular Python exceptions |
| 10 |
- Exceptions that are raised as part of the request handling, i.e. |
| 11 |
exceptions in route handlers, dependencies, and middleware, that should be returned as a response to the end user |
| 12 |
|
| 13 |
Configuration Exceptions |
| 14 |
------------------------ |
| 15 |
|
| 16 |
For missing extra dependencies, Litestar will raise either |
| 17 |
:class:`MissingDependencyException <litestar.exceptions.MissingDependencyException>`. For example, if you try to use the |
| 18 |
:ref:`SQLAlchemyPlugin <plugins>` without having SQLAlchemy installed, this will be raised when you |
| 19 |
start the application. |
| 20 |
|
| 21 |
For other configuration issues, Litestar will raise |
| 22 |
:class:`ImproperlyConfiguredException <litestar.exceptions.ImproperlyConfiguredException>` with a message explaining the |
| 23 |
issue. |
| 24 |
|
| 25 |
Application Exceptions |
| 26 |
---------------------- |
| 27 |
|
| 28 |
For application exceptions, Litestar uses the class :class:`~litestar.exceptions.http_exceptions.HTTPException`, |
| 29 |
which inherits from :class:`~litestar.exceptions.LitestarException`. This exception will be serialized |
| 30 |
into a JSON response of the following schema: |
| 31 |
|
| 32 |
.. code-block:: json |
| 33 |
|
| 34 |
{ |
| 35 |
"status_code": 500, |
| 36 |
"detail": "Internal Server Error", |
| 37 |
"extra": {} |
| 38 |
} |
| 39 |
|
| 40 |
Litestar also offers several pre-configured ``HTTPException`` subclasses with pre-set error codes that you can use, such as: |
| 41 |
|
| 42 |
|
| 43 |
.. :currentmodule:: litestar.exceptions.http_exceptions |
| 44 |
|
| 45 |
+----------------------------------------+-------------+------------------------------------------+ |
| 46 |
| Exception | Status code | Description | |
| 47 |
+========================================+=============+==========================================+ |
| 48 |
| :class:`ImproperlyConfiguredException` | 500 | Used internally for configuration errors | |
| 49 |
+----------------------------------------+-------------+------------------------------------------+ |
| 50 |
| :class:`ValidationException` | 400 | Raised when validation or parsing failed | |
| 51 |
+----------------------------------------+-------------+------------------------------------------+ |
| 52 |
| :class:`NotAuthorizedException` | 401 | HTTP status code 401 | |
| 53 |
+----------------------------------------+-------------+------------------------------------------+ |
| 54 |
| :class:`PermissionDeniedException` | 403 | HTTP status code 403 | |
| 55 |
+----------------------------------------+-------------+------------------------------------------+ |
| 56 |
| :class:`NotFoundException` | 404 | HTTP status code 404 | |
| 57 |
+----------------------------------------+-------------+------------------------------------------+ |
| 58 |
| :class:`InternalServerException` | 500 | HTTP status code 500 | |
| 59 |
+----------------------------------------+-------------+------------------------------------------+ |
| 60 |
| :class:`ServiceUnavailableException` | 503 | HTTP status code 503 | |
| 61 |
+----------------------------------------+-------------+------------------------------------------+ |
| 62 |
|
| 63 |
.. :currentmodule:: None |
| 64 |
|
| 65 |
When a value fails validation, the result will be a :class:`~litestar.exceptions.http_exceptions.ValidationException` with the ``extra`` key set to the validation error message. |
| 66 |
|
| 67 |
.. warning:: All validation error messages will be made available for the API consumers by default. |
| 68 |
If this is not your intent, adjust the exception contents. |
| 69 |
|
| 70 |
|
| 71 |
Exception handling |
| 72 |
------------------ |
| 73 |
|
| 74 |
Litestar handles all errors by default by transforming them into **JSON responses**. If the errors are **instances of** |
| 75 |
:class:`~litestar.exceptions.http_exceptions.HTTPException`, the responses will include the appropriate ``status_code``. |
| 76 |
Otherwise, the responses will default to ``500 - "Internal Server Error"``. |
| 77 |
|
| 78 |
|
| 79 |
The following handler for instance will default to ``MediaType.TEXT`` so the exception will be raised as text. |
| 80 |
|
| 81 |
.. literalinclude:: /examples/exceptions/implicit_media_type.py |
| 82 |
:language: python |
| 83 |
|
| 84 |
You can customize exception handling by passing a dictionary, mapping either status codes |
| 85 |
or exception classes to callables. For example, if you would like to replace the default |
| 86 |
exception handler with a handler that returns plain-text responses you could do this: |
| 87 |
|
| 88 |
.. literalinclude:: /examples/exceptions/override_default_handler.py |
| 89 |
:language: python |
| 90 |
|
| 91 |
|
| 92 |
The above will define a top level exception handler that will apply the ``plain_text_exception_handler`` function to all |
| 93 |
exceptions that inherit from ``HTTPException``. You could of course be more granular: |
| 94 |
|
| 95 |
.. literalinclude:: /examples/exceptions/per_exception_handlers.py |
| 96 |
:language: python |
| 97 |
|
| 98 |
|
| 99 |
The choice whether to use a single function that has switching logic inside it, or multiple functions depends on your |
| 100 |
specific needs. |
| 101 |
|
| 102 |
|
| 103 |
Exception handling layers |
| 104 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 105 |
|
| 106 |
Since Litestar allows users to define both exception handlers and middlewares in a layered fashion, i.e. on individual |
| 107 |
route handlers, controllers, routers, or the app layer, multiple layers of exception handlers are required to ensure that |
| 108 |
exceptions are handled correctly: |
| 109 |
|
| 110 |
|
| 111 |
.. figure:: /images/exception-handlers.jpg |
| 112 |
:width: 400px |
| 113 |
|
| 114 |
Exception Handlers |
| 115 |
|
| 116 |
|
| 117 |
As a result of the above structure, the exceptions raised by the ASGI Router itself, namely ``404 Not Found`` |
| 118 |
and ``405 Method Not Allowed`` are handled only by exception handlers defined on the app layer. Thus, if you want to affect |
| 119 |
these exceptions, you will need to pass the exception handlers for them to the Litestar constructor and cannot use other |
| 120 |
layers for this purpose. |
| 121 |
|
| 122 |
Litestar supports defining exception handlers on all layers of the app, with the lower layers overriding layer above |
| 123 |
them. In the following example, the exception handler for the route handler function will only handle |
| 124 |
the ``ValidationException`` occurring within that route handler: |
| 125 |
|
| 126 |
.. literalinclude:: /examples/exceptions/layered_handlers.py |
| 127 |
:language: python |