|
| 1 | +import json |
| 2 | +from fastapi import FastAPI, Request |
| 3 | +from fastapi.responses import JSONResponse |
| 4 | +from fastapi.exceptions import HTTPException |
| 5 | +from starlette.exceptions import HTTPException as StarletteHTTPException |
| 6 | + |
| 7 | +from http import HTTPStatus |
| 8 | + |
| 9 | +from config.setup_logs.logging import logger |
| 10 | +from api_v1.exeptions import ValidationError |
| 11 | + |
| 12 | + |
| 13 | +def register_errors(app: FastAPI) -> None: |
| 14 | + @app.exception_handler(ValidationError) |
| 15 | + async def validation_error_handler( |
| 16 | + request: Request, |
| 17 | + exc: ValidationError, |
| 18 | + ): |
| 19 | + """ |
| 20 | + Логирование всех ValidationError |
| 21 | + """ |
| 22 | + logger.opt(exception=True).warning(exc) |
| 23 | + response = dict( |
| 24 | + status=False, |
| 25 | + error_code=exc.status_code, |
| 26 | + message=exc.detail, |
| 27 | + ) |
| 28 | + return JSONResponse(response) |
| 29 | + |
| 30 | + @app.exception_handler(HTTPException) |
| 31 | + async def http_error_handler( |
| 32 | + request: Request, |
| 33 | + exc: HTTPException, |
| 34 | + ): |
| 35 | + """ |
| 36 | + Логирование всех HTTPException |
| 37 | + """ |
| 38 | + logger.opt(exception=True).warning(exc) |
| 39 | + response = dict( |
| 40 | + status=False, |
| 41 | + error_code=exc.status_code, |
| 42 | + message=exc.detail, |
| 43 | + ) |
| 44 | + return JSONResponse(response) |
| 45 | + |
| 46 | + @app.exception_handler(Exception) |
| 47 | + async def error_handler( |
| 48 | + request: Request, |
| 49 | + exc: Exception, |
| 50 | + ): |
| 51 | + """ |
| 52 | + Логирование всех Exception |
| 53 | + """ |
| 54 | + logger.exception(exc) |
| 55 | + response = dict( |
| 56 | + status=False, |
| 57 | + error_code=500, |
| 58 | + message=HTTPStatus(500).phrase, |
| 59 | + ) |
| 60 | + return JSONResponse(response) |
| 61 | + |
| 62 | + @app.exception_handler(StarletteHTTPException) |
| 63 | + async def validation_error_handler( |
| 64 | + request: Request, |
| 65 | + exc: StarletteHTTPException, |
| 66 | + ): |
| 67 | + """ |
| 68 | + Логирование всех StarletteHTTPException |
| 69 | + """ |
| 70 | + logger.opt(exception=True).warning(exc) |
| 71 | + response = dict( |
| 72 | + status=False, |
| 73 | + error_code=exc.status_code, |
| 74 | + message=exc.detail, |
| 75 | + ) |
| 76 | + return JSONResponse(response) |
0 commit comments