Error handling
Earlier on in this chapter, we learned what status codes are and how they are useful in informing the client about the request status. Requests can return erroneous responses, and these responses can be ugly or have insufficient information about the cause of failure.
Errors from requests can result from attempting to access non-existent resources, protected pages without sufficient permissions, and even server errors. Errors in FastAPI are handled by raising an exception using FastAPI’s HTTPException
class.
What Is an HTTP Exception?
An HTTP exception is an event that is used to indicate a fault or issue in the request flow.
The HTTPException
class takes three arguments:
status_code
: The status code to be returned for this disruptiondetail
: Accompanying message to be sent to the clientheaders
: An optional parameter for responses requiring headers
In our to-do route path definitions, we return a message when a to-do can’...