Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

589
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda