|
| 1 | +"""API exception handling module.""" |
| 2 | + |
| 3 | +from typing import Dict, Any |
| 4 | +from fastapi import HTTPException, Request |
| 5 | +from fastapi.responses import JSONResponse |
| 6 | +from fastapi.exceptions import RequestValidationError |
| 7 | + |
| 8 | +from .schemas import ErrorResponse, StatusCode |
| 9 | + |
| 10 | + |
| 11 | +class APIException(Exception): |
| 12 | + """Custom API exception base class.""" |
| 13 | + |
| 14 | + def __init__(self, code: StatusCode, message: str, details: Dict[str, Any] = None): |
| 15 | + self.code = code |
| 16 | + self.message = message |
| 17 | + self.details = details or {} |
| 18 | + super().__init__(message) |
| 19 | + |
| 20 | + |
| 21 | +class UnauthorizedException(APIException): |
| 22 | + """Unauthorized exception.""" |
| 23 | + |
| 24 | + def __init__(self, message: str = "Unauthorized access"): |
| 25 | + super().__init__(StatusCode.UNAUTHORIZED, message) |
| 26 | + |
| 27 | + |
| 28 | +class NotFoundException(APIException): |
| 29 | + """Resource not found exception.""" |
| 30 | + |
| 31 | + def __init__(self, message: str = "Resource not found"): |
| 32 | + super().__init__(StatusCode.NOT_FOUND, message) |
| 33 | + |
| 34 | + |
| 35 | +class ForbiddenException(APIException): |
| 36 | + """Forbidden access exception.""" |
| 37 | + |
| 38 | + def __init__(self, message: str = "Forbidden access"): |
| 39 | + super().__init__(StatusCode.FORBIDDEN, message) |
| 40 | + |
| 41 | + |
| 42 | +class InternalServerException(APIException): |
| 43 | + """Internal server error exception.""" |
| 44 | + |
| 45 | + def __init__(self, message: str = "Internal server error"): |
| 46 | + super().__init__(StatusCode.INTERNAL_ERROR, message) |
| 47 | + |
| 48 | + |
| 49 | +async def api_exception_handler(request: Request, exc: APIException) -> JSONResponse: |
| 50 | + """API exception handler.""" |
| 51 | + return JSONResponse( |
| 52 | + status_code=200, # HTTP status code is always 200, error info is in response body |
| 53 | + content=ErrorResponse.create(code=exc.code, msg=exc.message).dict(), |
| 54 | + ) |
| 55 | + |
| 56 | + |
| 57 | +async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse: |
| 58 | + """HTTP exception handler.""" |
| 59 | + # Map HTTP status codes to our status codes |
| 60 | + status_code_mapping = { |
| 61 | + 400: StatusCode.BAD_REQUEST, |
| 62 | + 401: StatusCode.UNAUTHORIZED, |
| 63 | + 403: StatusCode.FORBIDDEN, |
| 64 | + 404: StatusCode.NOT_FOUND, |
| 65 | + 500: StatusCode.INTERNAL_ERROR, |
| 66 | + } |
| 67 | + |
| 68 | + api_code = status_code_mapping.get(exc.status_code, StatusCode.INTERNAL_ERROR) |
| 69 | + return JSONResponse( |
| 70 | + status_code=200, |
| 71 | + content=ErrorResponse.create(code=api_code, msg=str(exc.detail)).dict(), |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +async def validation_exception_handler( |
| 76 | + request: Request, exc: RequestValidationError |
| 77 | +) -> JSONResponse: |
| 78 | + """Request validation exception handler.""" |
| 79 | + # Extract validation error information |
| 80 | + error_details = [] |
| 81 | + for error in exc.errors(): |
| 82 | + error_details.append( |
| 83 | + { |
| 84 | + "field": ".".join(str(x) for x in error["loc"]), |
| 85 | + "message": error["msg"], |
| 86 | + "type": error["type"], |
| 87 | + } |
| 88 | + ) |
| 89 | + |
| 90 | + return JSONResponse( |
| 91 | + status_code=200, |
| 92 | + content=ErrorResponse.create( |
| 93 | + code=StatusCode.BAD_REQUEST, |
| 94 | + msg=f"Request parameter validation failed: {'; '.join([f'{e["field"]}: {e["message"]}' for e in error_details])}", |
| 95 | + ).dict(), |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +async def general_exception_handler(request: Request, exc: Exception) -> JSONResponse: |
| 100 | + """General exception handler.""" |
| 101 | + return JSONResponse( |
| 102 | + status_code=200, |
| 103 | + content=ErrorResponse.create( |
| 104 | + code=StatusCode.INTERNAL_ERROR, |
| 105 | + msg="Internal server error, please try again later", |
| 106 | + ).dict(), |
| 107 | + ) |
0 commit comments