unhandled_exception_handler.py 594 B

12345678910111213141516171819
  1. import logging
  2. from starlette.middleware.base import BaseHTTPMiddleware
  3. from app.providers.response import ErrorResponse
  4. # Bug: exception_handler unable to catch Exception
  5. # https://github.com/tiangolo/fastapi/issues/4025
  6. class UnhandledExceptionHandlingMiddleware(BaseHTTPMiddleware):
  7. """
  8. 处理其他未知异常
  9. """
  10. async def dispatch(self, request, call_next):
  11. try:
  12. return await call_next(request)
  13. except Exception as e:
  14. logging.exception(e)
  15. return ErrorResponse(500, "internal_server_error", "Internal Server Error")