1
1
"""Error handling."""
2
2
3
3
import logging
4
- from typing import Callable , Dict , Type
4
+ from typing import Callable , Dict , Type , TypedDict
5
5
6
6
from fastapi import FastAPI
7
7
from fastapi .exceptions import RequestValidationError
30
30
}
31
31
32
32
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
+
33
47
def exception_handler_factory (status_code : int ) -> Callable :
34
48
"""Create a FastAPI exception handler for a particular status code.
35
49
@@ -43,7 +57,10 @@ def exception_handler_factory(status_code: int) -> Callable:
43
57
def handler (request : Request , exc : Exception ):
44
58
"""I handle exceptions!!."""
45
59
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
+ )
47
64
48
65
return handler
49
66
@@ -69,8 +86,8 @@ def request_validation_exception_handler(
69
86
request : Request , exc : RequestValidationError
70
87
) -> JSONResponse :
71
88
return JSONResponse (
89
+ content = ErrorResponse (code = exc .__class__ .__name__ , description = str (exc )),
72
90
status_code = status .HTTP_400_BAD_REQUEST ,
73
- content = {"detail" : exc .errors ()},
74
91
)
75
92
76
93
app .add_exception_handler (
0 commit comments