Adds Exception Handlers

This commit is contained in:
2024-05-21 19:23:49 -03:00
parent 458d63a6c5
commit 0acf167d12
5 changed files with 48 additions and 2 deletions

View File

@@ -1,13 +1,22 @@
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
from storage_service.config.config_allowed_origins import get_allowed_origins from storage_service.config.config_allowed_origins import get_allowed_origins
from storage_service.controller.health_checker_controller import health_router from storage_service.controller.health_checker_controller import health_router
from storage_service.controller.storage_controller import s3_router from storage_service.controller.storage_controller import s3_router
from fastapi import FastAPI from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from storage_service.utils.exception_handler import http_exception_handler, validation_exception_handler
app = FastAPI() app = FastAPI()
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=get_allowed_origins(), allow_origins=get_allowed_origins(),

View File

@@ -0,0 +1,2 @@
from .http_exception_handler import http_exception_handler
from .validation_exception_handler import validation_exception_handler

View File

@@ -0,0 +1,15 @@
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"message": exc.detail,
"status_code": exc.status_code,
}
},
)

View File

@@ -0,0 +1,20 @@
from fastapi.exceptions import RequestValidationError
from starlette import status
from starlette.requests import Request
from starlette.responses import JSONResponse
async def validation_exception_handler(request: Request, exc: RequestValidationError):
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
return JSONResponse(
status_code=status_code,
content={
"error": {
"details": {
"body": exc.body,
"errors": exc.errors(),
},
"status_code": status_code,
}
},
)

View File

@@ -4,5 +4,5 @@ from fastapi import HTTPException, status
class FileNotFoundException(HTTPException): class FileNotFoundException(HTTPException):
def __init__(self, message: str): def __init__(self, message: str):
super().__init__( super().__init__(
status.HTTP_400_BAD_REQUEST, detail=message status.HTTP_404_NOT_FOUND, detail=message
) )