add logging to error handlers

This commit is contained in:
thatmattlove 2024-03-03 00:20:54 -05:00
parent ec5c0362e3
commit 213da6380b

View file

@ -1,5 +1,7 @@
"""API Error Handlers."""
from hyperglass.log import log
# Third Party
from fastapi import Request
from starlette.responses import JSONResponse
@ -11,6 +13,9 @@ from hyperglass.state import use_state
async def default_handler(request: Request, exc: BaseException) -> JSONResponse:
"""Handle uncaught errors."""
state = use_state()
log.critical(
"{method} {path} {detail!s}", method=request.method, path=request.url.path, detail=exc
)
return JSONResponse(
{"output": state.params.messages.general, "level": "danger", "keywords": []},
status_code=500,
@ -19,7 +24,9 @@ async def default_handler(request: Request, exc: BaseException) -> JSONResponse:
async def http_handler(request: Request, exc: BaseException) -> JSONResponse:
"""Handle web server errors."""
log.critical(
"{method} {path} {detail}", method=request.method, path=request.url.path, detail=exc.detail
)
return JSONResponse(
{"output": exc.detail, "level": "danger", "keywords": []},
status_code=exc.status_code,
@ -28,6 +35,9 @@ async def http_handler(request: Request, exc: BaseException) -> JSONResponse:
async def app_handler(request: Request, exc: BaseException) -> JSONResponse:
"""Handle application errors."""
log.critical(
"{method} {path} {detail}", method=request.method, path=request.url.path, detail=exc.message
)
return JSONResponse(
{"output": exc.message, "level": exc.level, "keywords": exc.keywords},
status_code=exc.status_code,
@ -37,6 +47,12 @@ async def app_handler(request: Request, exc: BaseException) -> JSONResponse:
async def validation_handler(request: Request, exc: BaseException) -> JSONResponse:
"""Handle Pydantic validation errors raised by FastAPI."""
error = exc.errors()[0]
log.critical(
"{method} {path} {detail}",
method=request.method,
path=request.url.path,
detail=error["msg"],
)
return JSONResponse(
{"output": error["msg"], "level": "error", "keywords": error["loc"]},
status_code=422,