error-handling
Error Hanlding
- use
route.get(errors=VioletsAreBlue)to declare a endpoint response
class VioletsAreBlue(HTTPException[str]):
"how about you?"
__status__ = 418
@lhl.post(errors=VioletsAreBlue)
async def roses_are_red():
raise VioletsAreBlue("I am a pythonista")
- use
lihil.problems.problem_solveras decorator to register a error handler, error will be parsed as Problem Detail.
from lihil.problems import problem_solver
# NOTE: you can use type union for exc, e.g. UserNotFound | status.NOT_FOUND
@problem_solver
def handle_404(req: Request, exc: Literal[404]):
return Response("resource not found", status_code=404)
A solver that handles a specific exception type (e.g., UserNotFound) takes precedence over a solver that handles the status code (e.g., 404).
Exception-Problem mapping
lihil automatically generates a response and documentation based on your HTTPException,
Here is the generated doc for the endpoint roses_are_red
click url under External documentation tab
we will see the detailed problem page
By default, every endpoint will have at least one response with code 422 for InvalidRequestErrors.
Here is one example response of InvalidRequestErrors.
{
"type_": "invalid-request-errors",
"status": 422,
"title": "Missing",
"detail": [
{
"type": "MissingRequestParam",
"location": "query",
"param": "q",
"message": "Param is Missing"
},
{
"type": "MissingRequestParam",
"location": "query",
"param": "r",
"message": "Param is Missing"
}
],
"instance": "/users"
}
- To alter the creation of the response, use
lihil.problems.problem_solverto register your solver. - To change the documentation, override
DetailBase.__json_example__andDetailBase.__problem_detail__. - To extend the error detail, provide typevar when inheriting
HTTPException[T].