Skip to content

Commit

Permalink
perf: Update exception handling methods.
Browse files Browse the repository at this point in the history
  • Loading branch information
amisadmin committed Sep 10, 2023
1 parent 6c025d0 commit 2cb01eb
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 5 deletions.
56 changes: 52 additions & 4 deletions fastapi_amis_admin/admin/handlers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import typing

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.exceptions import RequestValidationError, ValidationException
from fastapi.utils import is_body_allowed_for_status_code
from pydantic import ValidationError
from starlette.background import BackgroundTask
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import Response
from starlette.status import (
HTTP_417_EXPECTATION_FAILED,
HTTP_422_UNPROCESSABLE_ENTITY,
HTTP_500_INTERNAL_SERVER_ERROR,
)
from starlette.types import Receive, Scope, Send

from fastapi_amis_admin.crud import BaseApiOut
from fastapi_amis_admin.utils.translation import i18n as _
Expand All @@ -23,12 +30,34 @@ def register_exception_handlers(app: FastAPI, **kwargs):
"""global exception catch"""
app.add_exception_handler(RequestValidationError, handler=request_validation_exception_handler)
app.add_exception_handler(HTTPException, handler=http_exception_handler)
app.add_exception_handler(ValidationException, handler=inner_validation_exception_handler)
app.add_exception_handler(ValidationError, handler=inner_validation_exception_handler)
app.add_exception_handler(Exception, handler=server_error_handler)


class JSONResponseWithException(JSONResponse):
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: typing.Optional[typing.Dict[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[BackgroundTask] = None,
exc: Exception = None,
) -> None:
self.exc = exc
super().__init__(content, status_code, headers, media_type, background)

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await super().__call__(scope, receive, send)
if self.exc is not None:
raise self.exc


def make_error_response(status: int, msg="", **extra):
def make_error_response(status: int, msg="", *, exc: Exception = None, **extra):
"""Construct an error response"""
result = BaseApiOut(status=status, msg=msg, **extra)
return JSONResponse(content=result.dict())
return JSONResponseWithException(content=result.dict(), exc=exc)


async def http_exception_handler(request: Request, exc: HTTPException):
Expand All @@ -44,7 +73,26 @@ async def request_validation_exception_handler(request: Request, exc: RequestVal
"""Request parameter validation exception"""
return make_error_response(
status=HTTP_422_UNPROCESSABLE_ENTITY,
msg=_("Request parameter validation error"),
msg=_("Request parameter validation exception"),
body=exc.body,
errors=exc.errors(),
)


async def inner_validation_exception_handler(request: Request, exc: typing.Union[ValidationException, ValidationError]):
"""Internal data validation exception.Output a json response and throw the exception again."""
return make_error_response(
status=HTTP_417_EXPECTATION_FAILED,
msg=_("Internal data validation exception"),
errors=exc.errors(),
exc=exc,
)


async def server_error_handler(request: Request, exc: Exception):
"""Internal server exception.Output a json response and throw the exception again."""
return make_error_response(
status=HTTP_500_INTERNAL_SERVER_ERROR,
msg=_("Internal server exception"),
exc=exc,
)
Binary file modified fastapi_amis_admin/locale/de_DE/LC_MESSAGES/messages.mo
Binary file not shown.
5 changes: 5 additions & 0 deletions fastapi_amis_admin/locale/de_DE/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,8 @@ msgstr "Home"
msgid "Request parameter validation error"
msgstr "Fehler bei der Validierung der Anfrageparameter"

msgid "Internal data validation exception"
msgstr "Interne Datenvalidierungsausnahme"

msgid "Internal server exception"
msgstr "Interne Serverausnahme"
Binary file modified fastapi_amis_admin/locale/zh_CN/LC_MESSAGES/messages.mo
Binary file not shown.
7 changes: 6 additions & 1 deletion fastapi_amis_admin/locale/zh_CN/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ msgstr "否"
msgid "Home"
msgstr "首页"

msgid "Request parameter validation error"
msgid "Request parameter validation exception"
msgstr "请求参数验证错误"

msgid "Internal data validation exception"
msgstr "内部数据验证异常"

msgid "Internal server exception"
msgstr "内部服务器异常"

0 comments on commit 2cb01eb

Please sign in to comment.