python从apirouter引发异常不会运行异常处理程序,而是返回500个内部服务器错误快速api

djp7away  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(370)

我正在使用添加到fastapi的api路由器在fastapi中引发一个自定义异常。我正在定义异常类和处理程序,并使用以下代码添加它们。这是工作之前,现在我不太清楚是什么问题。添加了中间件,所以这可能就是问题所在?

  1. app = FastAPI()
  2. origins = [
  3. "*", # Restrict these in the future?
  4. ]
  5. app.include_router(memblock_router.router)
  6. app.include_router(event_router.router)
  7. app.add_exception_handler(UnauthorizedException, unauthorized_exception_handler)
  8. app.add_exception_handler(InvalidParameterException, invalid_parameter_exception_handler)
  9. app.add_exception_handler(DatabaseException, database_exception_handler)
  10. app.add_exception_handler(ElasticsearchException, elasticsearch_exception_handler)
  11. app.add_exception_handler(ParsingException, parsing_exception_handler)
  12. app.add_exception_handler(ForbiddenErrorMessage, forbidden_error_message_exception)
  13. app.add_exception_handler(UnsupportedErrorMessage, unsupported_message)
  14. app.add_exception_handler(RequestValidationError, validation_exception_handler)
  15. app.add_middleware(
  16. CORSMiddleware,
  17. allow_origins=origins,
  18. allow_credentials=True,
  19. allow_methods=["*"],
  20. allow_headers=["*"],
  21. )

我是这样定义异常和处理程序的

  1. class UnauthorizedException(Exception):
  2. pass
  3. def unauthorized_exception_handler(request: Request, exc: UnauthorizedException):
  4. print(str(traceback.format_exc()))
  5. return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED,
  6. content={"error": "unauthorized"},
  7. headers=get_response_headers())

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题