Managing API-related exceptions
The FastAPI framework has a built-in exception handler derived from its Starlette toolkit that always returns default JSON responses whenever HTTPException
is encountered during the execution of the REST API operation. For instance, accessing the API at http://localhost:8000/ch02/user/login
without providing the username
and password
will give us the default JSON output depicted in Figure 2.2:
Figure 2.2 – The default exception result
In some rare cases, the framework sometimes chooses to return the HTTP response status instead of the default JSON content. But developers can still opt to override these default handlers to choose which responses to return whenever a specific exception cause happens.
Let us now explore how to formulate a standardized and appropriate way of managing runtime errors in our API implementation.
A single status code response
One way of managing the exception-handling mechanism of...