http_error.py 783 B

1234567891011121314151617181920
  1. from fastapi import status
  2. from fastapi.encoders import jsonable_encoder
  3. from fastapi.responses import JSONResponse
  4. from starlette.exceptions import HTTPException
  5. from utils.response import resp_400
  6. async def httpExceptionHandler(request, exc: HTTPException) -> JSONResponse:
  7. """自定义处理HTTPException"""
  8. print("request:", request)
  9. print("status_code:", exc.status_code)
  10. if exc.status_code == status.HTTP_404_NOT_FOUND:
  11. # 处理404错误
  12. return resp_400(data=[], message="接口路由不存在")
  13. elif exc.status_code == status.HTTP_405_METHOD_NOT_ALLOWED:
  14. # 处理405错误
  15. return resp_400(data=[], message="请求方式错误,请查看文档确认")
  16. else:
  17. return resp_400(data=[], message=str(exc))