github-actions[bot]
Automated Deploy: bc9f9bdebdd9f5ac1fd6eca496428aa61a69a2cc
6437539
Raw History Blame Contribute Delete
5.16 kB
"""One error envelope for every response: {"error": {"code", "message", "fields"?}}.
Services raise AppError subclasses; the handlers below turn them (and request validation errors) into JSON.
Messages are safe to show in the app.
"""
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import DBAPIError
from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
from starlette.exceptions import HTTPException as StarletteHTTPException
log = logging.getLogger(__name__)
class AppError(Exception):
status_code = 500
code = "INTERNAL"
message = "Something went wrong. Please try again."
def __init__(self, message: str | None = None, *, code: str | None = None, fields: dict[str, str] | None = None):
self.message = message or self.message
self.code = code or self.code
self.fields = fields
super().__init__(self.message)
class ValidationFailed(AppError):
status_code, code, message = 400, "VALIDATION", "Some fields are not valid."
class Unauthenticated(AppError):
status_code, code, message = 401, "UNAUTHENTICATED", "Please sign in again."
class PlanLimitReached(AppError):
status_code, code, message = 402, "PLAN_LIMIT", "The free plan includes 20 analyses a week."
class Forbidden(AppError):
status_code, code, message = 403, "FORBIDDEN", "You do not have access to this."
class NotFound(AppError):
status_code, code, message = 404, "NOT_FOUND", "We couldn't find that."
class Conflict(AppError):
status_code, code, message = 409, "CONFLICT", "This conflicts with existing data."
class TooLarge(AppError):
status_code, code, message = 413, "TOO_LARGE", "The file is too large."
class Unprocessable(AppError):
status_code, code, message = 422, "UNPROCESSABLE", "The request could not be processed."
class RateLimited(AppError):
status_code, code, message = 429, "RATE_LIMITED", "Too many attempts. Please wait a minute and try again."
class ServiceUnavailable(AppError):
status_code, code, message = 503, "UNAVAILABLE", "A service we depend on is unavailable. Please try again."
def _body(code: str, message: str, fields: dict[str, str] | None = None) -> dict:
error: dict = {"code": code, "message": message}
if fields:
error["fields"] = fields
return {"error": error}
def _field_path(loc: tuple) -> str:
parts = [str(p) for p in loc if p not in ("body", "query", "path", "header")]
path = ""
for p in parts:
path += f"[{p}]" if p.isdigit() else (f".{p}" if path else p)
return path or "request"
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def _app_error(_: Request, exc: AppError) -> JSONResponse:
return JSONResponse(_body(exc.code, exc.message, exc.fields), status_code=exc.status_code)
@app.exception_handler(StarletteHTTPException)
async def _http_error(_: Request, exc: StarletteHTTPException) -> JSONResponse:
"""Routing errors (unknown path, wrong method) use the same envelope as everything else."""
codes = {404: ("NOT_FOUND", NotFound.message), 405: ("METHOD_NOT_ALLOWED", "This method is not allowed here.")}
code, message = codes.get(exc.status_code, ("HTTP_ERROR", str(exc.detail)))
return JSONResponse(_body(code, message), status_code=exc.status_code, headers=getattr(exc, "headers", None))
@app.exception_handler(RequestValidationError)
async def _validation_error(_: Request, exc: RequestValidationError) -> JSONResponse:
fields: dict[str, str] = {}
for err in exc.errors():
fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value."))
return JSONResponse(_body(ValidationFailed.code, ValidationFailed.message, fields), status_code=400)
@app.exception_handler(SQLAlchemyTimeoutError)
async def _pool_exhausted(_: Request, exc: SQLAlchemyTimeoutError) -> JSONResponse:
log.warning("database pool exhausted: %s", exc)
return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
headers={"Retry-After": "2"})
@app.exception_handler(Exception)
async def _unexpected(_: Request, exc: Exception) -> JSONResponse:
return unexpected_error_response(exc)
DB_BUSY_MARKERS = ("max clients reached", "too many connections", "remaining connection slots")
def unexpected_error_response(exc: Exception) -> JSONResponse:
"""500 for bugs; 503 (retryable) when the database has no free connection."""
if isinstance(exc, DBAPIError) and any(m in str(exc).lower() for m in DB_BUSY_MARKERS):
log.warning("database has no free connection: %s", str(exc).splitlines()[0])
return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
headers={"Retry-After": "2"})
log.exception("unhandled error", exc_info=exc)
return JSONResponse(_body(AppError.code, AppError.message), status_code=500)