Custom STAC-style exception handlers for FastAPI applications.
register_stac_exception_handlers(app)
Attach STAC-style error handlers to the given FastAPI app.
Source code in docs/rs-server/services/common/rs_server_common/utils/error_handlers.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 | def register_stac_exception_handlers(app: FastAPI):
"""Attach STAC-style error handlers to the given FastAPI app."""
def _build_stac_error_response(exc: HTTPException | StarletteHTTPException) -> JSONResponse:
"""Build STAC-style error response."""
phrase = HTTPStatus(exc.status_code).phrase
code = "".join(word.title() for word in phrase.split())
# Return STAC-compliant error format
payload: ErrorResponse = {
"code": code,
"description": exc.detail if isinstance(exc.detail, str) else str(exc.detail),
}
return JSONResponse(status_code=exc.status_code, content=payload)
@app.exception_handler(HTTPException)
async def http_exc_handler(_request: Request, exc: HTTPException):
"""Override HTTPException to return a STAC-style ErrorResponse."""
return _build_stac_error_response(exc)
@app.exception_handler(StarletteHTTPException)
async def starlette_http_exception_handler(_request: Request, exc: StarletteHTTPException):
"""Catch Starlette HTTPExceptions, including 404 from unknown routes."""
return _build_stac_error_response(exc)
|