# Create Custom Exception Handlers in FastAPI with Messages

> Define custom exception classes with message attributes in FastAPI and access them in exception handler functions to return clean JSON error responses

**URL:** https://sentry.io/answers/custom-exception-handling-in-fastapi/

---

## The Problem

I'm reworking a FastAPI project to use several custom exceptions rather than FastAPI's default `HTTPException`. I've defined the exception classes and handler functions. Here's an example:

```python
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import JSONResponse
from fastapi import Request

app = FastAPI()

class MyException(HTTPException):
    pass

@app.exception_handler(MyException)
def my_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": "404 file not found"})

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```
When I was using `HTTPException`s, I could pass a message to the exception, for example:

```python
raise HTTPException(status_code=404, detail="Item not found")
```

Is there a way to pass a message to custom exceptions?

## The Solution

An exception handler function takes two arguments: the request and the exception. The exception is an instance of the custom exception class. Like any custom class, we can define and assign attributes for our exceptions and access them in the exception handler. For example:

```python
class MyException(HTTPException):
    def __init__(self, message: str):  # define and assign a message attribute
        self.message = message

@app.exception_handler(MyException)
def my_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,
                        content={"message": exc.message})  # use the exc object's message attribute
```

Then we can provide an arbitrary message when we raise the exception, as was previously done with `HTTPException`:

```python
raise MyException(message="Can't find the item")
```

## Production Error Handling

While custom exception handlers help you return clean API responses during development, [python error handling](https://sentry.io/for/python/) in production requires visibility into when and why exceptions occur. Production environments surface error patterns you won't catch locally—specific user inputs that trigger validation errors, edge cases in business logic, or exceptions that only happen under concurrent load. Error monitoring tools automatically capture your custom exceptions with full context including request parameters, user information, and the execution path, helping you identify patterns and fix the root causes rather than just handling symptoms.

---

*Source: [sentry.io/answers/custom-exception-handling-in-fastapi/](https://sentry.io/answers/custom-exception-handling-in-fastapi/)*
