• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

490
Views
Fast API: Handling exceptions globally

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

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error