Spaces:
Sleeping
Sleeping
Download src/middleware/error_handler.py from farukhannan/flve: direct link, hf CLI and curl.
- Browser
- Download file 4.78 kB
-
https://huggingface.co/spaces/farukhannan/flve/resolve/main/src/middleware/error_handler.py
- Command line
-
hf download hf://spaces/farukhannan/flve/src/middleware/error_handler.py
-
curl -L -o error_handler.py https://huggingface.co/spaces/farukhannan/flve/resolve/main/src/middleware/error_handler.py
4.78 kB
| """ | |
| Custom error handlers to prevent server crashes from binary data in validation errors. | |
| """ | |
| import logging | |
| from typing import Any, Dict | |
| from fastapi import Request, status | |
| from fastapi.responses import JSONResponse | |
| from fastapi.exceptions import RequestValidationError | |
| from starlette.exceptions import HTTPException as StarletteHTTPException | |
| logger = logging.getLogger(__name__) | |
| def sanitize_validation_error(error_detail: Any) -> Any: | |
| """ | |
| Recursively sanitize validation error details to prevent binary data crashes. | |
| Converts bytes to safe string representations. | |
| """ | |
| if isinstance(error_detail, bytes): | |
| # Convert bytes to safe hex representation | |
| try: | |
| # Try UTF-8 decode first | |
| return error_detail.decode('utf-8', errors='replace') | |
| except Exception: | |
| # Fall back to hex representation for binary data | |
| return f"<binary data: {len(error_detail)} bytes>" | |
| elif isinstance(error_detail, dict): | |
| return {k: sanitize_validation_error(v) for k, v in error_detail.items()} | |
| elif isinstance(error_detail, list): | |
| return [sanitize_validation_error(item) for item in error_detail] | |
| elif isinstance(error_detail, tuple): | |
| return tuple(sanitize_validation_error(item) for item in error_detail) | |
| else: | |
| # For other types, return as-is | |
| return error_detail | |
| async def validation_exception_handler( | |
| request: Request, | |
| exc: RequestValidationError | |
| ) -> JSONResponse: | |
| """ | |
| Custom handler for RequestValidationError that prevents crashes from binary data. | |
| This replaces the default FastAPI handler which crashes when trying to | |
| JSON-encode validation errors containing binary data. | |
| """ | |
| try: | |
| # Get the validation errors | |
| errors = exc.errors() | |
| # Sanitize each error to remove binary data | |
| sanitized_errors = [] | |
| for error in errors: | |
| sanitized_error = {} | |
| for key, value in error.items(): | |
| if key == 'input' and isinstance(value, bytes): | |
| # Don't include large binary inputs in error response | |
| sanitized_error[key] = f"<binary data: {len(value)} bytes>" | |
| else: | |
| sanitized_error[key] = sanitize_validation_error(value) | |
| sanitized_errors.append(sanitized_error) | |
| # Log the error for debugging | |
| logger.warning( | |
| f"Validation error on {request.method} {request.url.path}: " | |
| f"{len(sanitized_errors)} error(s)" | |
| ) | |
| return JSONResponse( | |
| status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, | |
| content={ | |
| "detail": sanitized_errors, | |
| "message": "Request validation failed. Please check your input data." | |
| }, | |
| ) | |
| except Exception as e: | |
| # If sanitization itself fails, return a generic error | |
| logger.error(f"Error in validation exception handler: {e}", exc_info=True) | |
| return JSONResponse( | |
| status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, | |
| content={ | |
| "detail": "Request validation failed", | |
| "message": "Invalid request format or content" | |
| }, | |
| ) | |
| async def http_exception_handler( | |
| request: Request, | |
| exc: StarletteHTTPException | |
| ) -> JSONResponse: | |
| """ | |
| Custom handler for HTTP exceptions with safe error serialization. | |
| """ | |
| return JSONResponse( | |
| status_code=exc.status_code, | |
| content={ | |
| "detail": str(exc.detail), | |
| "message": "An error occurred processing your request" | |
| }, | |
| ) | |
| async def general_exception_handler( | |
| request: Request, | |
| exc: Exception | |
| ) -> JSONResponse: | |
| """ | |
| Catch-all exception handler to prevent unhandled crashes. | |
| NOTE: HTTPException should be handled by http_exception_handler, not here. | |
| """ | |
| # Don't catch HTTPException here - let it be handled by http_exception_handler | |
| from fastapi import HTTPException as FastAPIHTTPException | |
| if isinstance(exc, (StarletteHTTPException, FastAPIHTTPException)): | |
| # This should not happen, but if it does, re-raise it | |
| raise exc | |
| logger.error( | |
| f"Unhandled exception on {request.method} {request.url.path}: {exc}", | |
| exc_info=True | |
| ) | |
| return JSONResponse( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| content={ | |
| "detail": "Internal server error", | |
| "message": "An unexpected error occurred. Please try again." | |
| }, | |
| ) | |