circuit

3 Ways to Handle Errors in FastAPI That You Need to Know




Over the past couple of months, I have been writing a lot about FastAPI and how awesome it is. Yet, the one thing that has been severely lacking in most of my articles is error handling. I usually would just talk about the main point of the article and mention that it should be added in later. The few times that I would include error handling, it would be done incorrectly. Essentially, I was always returning a status of 200 regardless of the error. This lack of proper error handling has made me determined to explain what I was doing wrong and talk about some ways that error handling could be implemented.

1. HTTPException

This function ships with the fastapi module. Therefore, in order to start using it, we just need to import it.

from fastapi import FastAPI, HTTPException

Once imported, it can be used by calling it along with the “raise” keyword.

raise HTTPException(status_code = 204, detail =  "")

Looking a little closer at what we are passing to the exception, there is the “status_code” and “detail”. As you probably guessed, the “status_code” gets assigned an HTTP status. This could be any code such as 204, 404, 500, etc. On the other hand, “detail” is a message that will show in the request’s response. Here is a bigger example of how the exception could be used.

async def test_http_exception(id):
     test_database = {
          "12345": "User1",
          "23456": "User2",
          "34567": "User3",
          "45678": "User4"
     }

     if id in test_database:
          print("Found it!!")
          return id
     else:
          raise HTTPException(status_code = 404, detail=  "Id not found")

The output in Postman will look a little something like this. Notice that the status in the response changed based on what we specified.

2. Create a Custom Exception

If you are feeling a little limited with options for HTTPException, you could always just create an exception handler yourself. To do so, start out by importing a couple of modules:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

After that, we need to create a class object so that we have something to hold exception data in:

class MyCustomException(Exception):
    def __init__(self, name: str):
        self.name = name

Next, we’ll create the exception handler and pass our class object to it:

[@app](http://twitter.com/app).exception_handler(MyCustomException)
async def MyCustomExceptionHandler(request: Request, exception: MyCustomException):
    return JSONResponse (status_code = 500, content = {"message": "Something critical happened"})

When an error occurs and raises this exception, the status should be 500 and print the message. Here is what raising the exception in an endpoint would look like:

[@app](http://twitter.com/app).get("/testapi/v1/{triggererror}")
async def GetTestException(triggererror: str):
    if triggererror == "yes":
        raise MyCustomException(name = triggererror)
    return results

If we were to test this in Postman, here's what the results would be;

3. Overriding HTTPException

Building out your own exception handler might seem like a lot of work. Another option would be to take an existing module and change its default settings. To accomplish this task, you would again need to import a few more modules:

from fastapi.responses import PlainTextResponse from starlette.exceptions import HTTPException as StarletteHTTPException

After that, we can create the exception handler that will override the raised exception:

[@app](http://twitter.com/app).exception_handler(StarletteHTTPException)
async def my_exception_handler(request, exception):
    return PlainTextResponse(str(exception.detail), status_code = exception.status_code)

In a nutshell, this handler will override the exception that gets passed to it and return it as plain text instead of JSON.

Conclusion

To sum things up, this list is by no means a complete set of options to handle error exceptions. Rather, this was to highlight just a couple of the different ways to handle exceptions in FastAPI. For most people (including myself) however, using the HTTPException function will suffice. Feel free to leave a comment about how you handle errors in FastAPI. Until next time, cheers!




Continue Learning