This module allows to throw exceptions in your code and send a proper HTTP response automatically to your client.
Depending on the REST Framework you use, your need to add exception handler(s) to your API.
If you want to document your API about those specific return types and the expected body, you can use layab to create your Starlette application.
You can also register all provided exceptions at once yourself using layaberr.starlette.exception_handlers
from starlette.applications import Starlette
import layaberr.starlette
app = Starlette(exception_handlers=layaberr.starlette.exception_handlers)
The following exceptions are available
In case your endpoint raises ValidationFailed, an HTTP error 400 (Bad Request) will be sent to the client.
This code:
from layaberr.starlette import ValidationFailed
received_data = None
raise ValidationFailed(received_data, message="This is the error message")
Will result in the following JSON response sent to the client:
[{"item": 1, "field_name": "", "messages": ["This is the error message"]}]
This code:
from layaberr.starlette import ValidationFailed
received_data = {"field 1": "value 1"}
raise ValidationFailed(received_data, errors={"field 1": ["Invalid value"]})
Will result in the following JSON response sent to the client:
[{"item": 1, "field_name": "field 1", "messages": ["Invalid value"]}]
This code:
from layaberr.starlette import ValidationFailed
received_data = [{"field 1": "value 1"}, {"field 1": "value 2"}]
raise ValidationFailed(received_data, errors={1: {"field 1": ["Invalid value"]}})
Will result in the following JSON response sent to the client:
[{"item": 2, "field_name": "field 1", "messages": ["Invalid value"]}]
In case your endpoint raises Unauthorized, an HTTP error 401 (Unauthorized) will be sent to the client.
This code:
from layaberr.starlette import Unauthorized
raise Unauthorized("The exception message")
Will result in the following JSON response sent to the client:
"The exception message"
In case your endpoint raises Forbidden, an HTTP error 403 (Forbidden) will be sent to the client.
This code:
from layaberr.starlette import Forbidden
raise Forbidden("The exception message")
Will result in the following JSON response sent to the client:
"The exception message"
In case your endpoint raises an Exception, an HTTP error 500 (Internal Server Error) will be sent to the client.
This code:
raise Exception("The exception message")
Will result in the following JSON response sent to the client:
"The exception message"
For the default handlers to work fine, you will have to disable the addition of "message" key within the exception results.
application.config["ERROR_INCLUDE_MESSAGE"] = False
- python 3.6+ must be installed
- Use pip to install module:
python -m pip install layaberr