Skip to content

Commit a9fd012

Browse files
author
Lev Rubel
committed
added headers attribute of exceptions through to response
1 parent 11a19c9 commit a9fd012

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

fastapi_contrib/exception_handlers.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ async def http_exception_handler(
115115
"""
116116
fields = getattr(exc, "fields", [])
117117
message = getattr(exc, "detail", "Validation error.")
118+
headers = getattr(exc, "headers", None)
118119
if message and not any(
119120
[message.endswith("."), message.endswith("?"), message.endswith("!")]
120121
):
@@ -124,7 +125,7 @@ async def http_exception_handler(
124125
"message": message,
125126
"fields": fields,
126127
}
127-
return UJSONResponse(data, status_code=exc.status_code)
128+
return UJSONResponse(data, status_code=exc.status_code, headers=headers)
128129

129130

130131
async def validation_exception_handler(
@@ -141,6 +142,7 @@ async def validation_exception_handler(
141142
:return: UJSONResponse with newly formatted error data
142143
"""
143144
status_code = getattr(exc, "status_code", 400)
145+
headers = getattr(exc, "headers", None)
144146
fields = raw_errors_to_fields(exc.raw_errors)
145147

146148
if fields:
@@ -155,7 +157,7 @@ async def validation_exception_handler(
155157
message = message + "." # pragma: no cover
156158

157159
data = {"error_codes": error_codes, "message": message, "fields": fields}
158-
return UJSONResponse(data, status_code=status_code)
160+
return UJSONResponse(data, status_code=status_code, headers=headers)
159161

160162

161163
async def not_found_error_handler(
@@ -164,9 +166,10 @@ async def not_found_error_handler(
164166
code = getattr(exc, "error_code", 404)
165167
detail = getattr(exc, "detail", "Not found.")
166168
fields = getattr(exc, "fields", [])
169+
headers = getattr(exc, "headers", None)
167170
status_code = getattr(exc, "status_code", 404)
168171
data = {"error_codes": [code], "message": detail, "fields": fields}
169-
return UJSONResponse(data, status_code=status_code)
172+
return UJSONResponse(data, status_code=status_code, headers=headers)
170173

171174

172175
async def internal_server_error_handler(
@@ -175,9 +178,10 @@ async def internal_server_error_handler(
175178
code = getattr(exc, "error_code", 500)
176179
detail = getattr(exc, "detail", "Internal Server Error.")
177180
fields = getattr(exc, "fields", [])
181+
headers = getattr(exc, "headers", None)
178182
status_code = getattr(exc, "status_code", 500)
179183
data = {"error_codes": [code], "message": detail, "fields": fields}
180-
return UJSONResponse(data, status_code=status_code)
184+
return UJSONResponse(data, status_code=status_code, headers=headers)
181185

182186

183187
def setup_exception_handlers(app: FastAPI) -> None:

0 commit comments

Comments
 (0)