Skip to content

Commit 6c22bad

Browse files
align error response with api spec (#361)
* align error response with api spec * lint * update changelog
1 parent c27bf82 commit 6c22bad

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

CHANGES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
* Update error response payloads to match the API spec. ([#361](https://github.com/stac-utils/stac-fastapi/pull/361))
6+
57
### Added
68

79
* Add hook to allow adding dependencies to routes. ([#295](https://github.com/stac-utils/stac-fastapi/pull/295))

stac_fastapi/api/stac_fastapi/api/errors.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Error handling."""
22

33
import logging
4-
from typing import Callable, Dict, Type
4+
from typing import Callable, Dict, Type, TypedDict
55

66
from fastapi import FastAPI
77
from fastapi.exceptions import RequestValidationError
@@ -30,6 +30,20 @@
3030
}
3131

3232

33+
class ErrorResponse(TypedDict):
34+
"""A JSON error response returned by the API.
35+
36+
The STAC API spec expects that `code` and `description` are both present in the payload.
37+
38+
Attributes:
39+
code: A code representing the error, semantics are up to implementor.
40+
description: A description of the error.
41+
"""
42+
43+
code: str
44+
description: str
45+
46+
3347
def exception_handler_factory(status_code: int) -> Callable:
3448
"""Create a FastAPI exception handler for a particular status code.
3549
@@ -43,7 +57,10 @@ def exception_handler_factory(status_code: int) -> Callable:
4357
def handler(request: Request, exc: Exception):
4458
"""I handle exceptions!!."""
4559
logger.error(exc, exc_info=True)
46-
return JSONResponse(content={"detail": str(exc)}, status_code=status_code)
60+
return JSONResponse(
61+
content=ErrorResponse(code=exc.__class__.__name__, description=str(exc)),
62+
status_code=status_code,
63+
)
4764

4865
return handler
4966

@@ -69,8 +86,8 @@ def request_validation_exception_handler(
6986
request: Request, exc: RequestValidationError
7087
) -> JSONResponse:
7188
return JSONResponse(
89+
content=ErrorResponse(code=exc.__class__.__name__, description=str(exc)),
7290
status_code=status.HTTP_400_BAD_REQUEST,
73-
content={"detail": exc.errors()},
7491
)
7592

7693
app.add_exception_handler(

0 commit comments

Comments
 (0)