Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

590
Vistas
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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda