Skip to content

Commit

Permalink
align error response with api spec (#361)
Browse files Browse the repository at this point in the history
* align error response with api spec

* lint

* update changelog
  • Loading branch information
geospatial-jeff authored Feb 28, 2022
1 parent c27bf82 commit 6c22bad
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

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

### Added

* Add hook to allow adding dependencies to routes. ([#295](https://github.com/stac-utils/stac-fastapi/pull/295))
Expand Down
23 changes: 20 additions & 3 deletions stac_fastapi/api/stac_fastapi/api/errors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Error handling."""

import logging
from typing import Callable, Dict, Type
from typing import Callable, Dict, Type, TypedDict

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
Expand Down Expand Up @@ -30,6 +30,20 @@
}


class ErrorResponse(TypedDict):
"""A JSON error response returned by the API.
The STAC API spec expects that `code` and `description` are both present in the payload.
Attributes:
code: A code representing the error, semantics are up to implementor.
description: A description of the error.
"""

code: str
description: str


def exception_handler_factory(status_code: int) -> Callable:
"""Create a FastAPI exception handler for a particular status code.
Expand All @@ -43,7 +57,10 @@ def exception_handler_factory(status_code: int) -> Callable:
def handler(request: Request, exc: Exception):
"""I handle exceptions!!."""
logger.error(exc, exc_info=True)
return JSONResponse(content={"detail": str(exc)}, status_code=status_code)
return JSONResponse(
content=ErrorResponse(code=exc.__class__.__name__, description=str(exc)),
status_code=status_code,
)

return handler

Expand All @@ -69,8 +86,8 @@ def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
content=ErrorResponse(code=exc.__class__.__name__, description=str(exc)),
status_code=status.HTTP_400_BAD_REQUEST,
content={"detail": exc.errors()},
)

app.add_exception_handler(
Expand Down

0 comments on commit 6c22bad

Please sign in to comment.