I am trying to get the exception_handler to work on a large project. However, the exception handler is not running as expected. Any suggestions on what I could be missing?
Simplified Project Structure:
project
__init__.py
main.py
common
__init__.py
ex_handler.py
I have the above project structure
app.py
app = FastAPI()
app.include_route(xyz)
I am importing this object into exception_handler.py which has code to handle all application-related exceptions
from project.main import app
@app.exception_handler(CustomException)
def handle_custom_ex(request: Request, exception: CustomException):
...
However, the exception handler is not running as expected. If I moved the exception_handler to app.py, it works.
Reference: https://fastapi.tiangolo.com/tutorial/handling-errors/?h=exception#install-custom-exception-handlers
I think you want to go the other way, i.e. import exception_handler
into your main.py
:
# exception_handler.py
class MyException(Exception):
def __init__(self, name: str):
self.name = name
# main.py
from project.common.exception_handler import MyException
...
In the docs, they define the class in their main.py
and then can use it in the FastAPI app
object.
Note you'll need to do this from any module where you want to use the custom exception class.