Skip to content

align error response with api spec #361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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