I am raising a custom exception in a Fast API using an API Router added to a Fast API. I am defining the exception class and handler and adding them both using the following code. It was working before and now I am not quite sure what is the issue. The middleware got added so maybe that is the issue?
app = FastAPI()
origins = [
"*", # Restrict these in the future?
]
app.include_router(memblock_router.router)
app.include_router(event_router.router)
app.add_exception_handler(UnauthorizedException, unauthorized_exception_handler)
app.add_exception_handler(InvalidParameterException, invalid_parameter_exception_handler)
app.add_exception_handler(DatabaseException, database_exception_handler)
app.add_exception_handler(ElasticsearchException, elasticsearch_exception_handler)
app.add_exception_handler(ParsingException, parsing_exception_handler)
app.add_exception_handler(ForbiddenErrorMessage, forbidden_error_message_exception)
app.add_exception_handler(UnsupportedErrorMessage, unsupported_message)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
I am defining the exceptions and handlers like so
class UnauthorizedException(Exception):
pass
def unauthorized_exception_handler(request: Request, exc: UnauthorizedException):
print(str(traceback.format_exc()))
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED,
content={"error": "unauthorized"},
headers=get_response_headers())
