Skip to content

Commit 25cb897

Browse files
lkk7peter-doggart
andauthored
Fix wrong status code and message on responses when handling HTTPExceptions (#570)
* Add possible fallback to response status code in error handling * Fix message attribute setting when handling HTTPExceptions * Add CHANGELOG.rst entry --------- Co-authored-by: Peter Doggart <[email protected]>
1 parent d348495 commit 25cb897

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

CHANGELOG.rst

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ Bug Fixes
3636

3737
* Fixing werkzeug 3 deprecated version import. Import is replaced by new style version check with importlib (#573) [Ryu-CZ]
3838
* Fixing flask 3.0+ compatibility of `ModuleNotFoundError: No module named 'flask.scaffold'` Import error. (#567) [Ryu-CZ]
39+
* Fix wrong status code and message on responses when handling `HTTPExceptions` (#569) [lkk7]
3940

4041

4142
.. _section-1.2.0:

flask_restx/api.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -718,9 +718,13 @@ def handle_error(self, e):
718718
got_request_exception.send(current_app._get_current_object(), exception=e)
719719

720720
if isinstance(e, HTTPException):
721-
code = HTTPStatus(e.code)
721+
code = None
722+
if e.code is not None:
723+
code = HTTPStatus(e.code)
724+
elif e.response is not None:
725+
code = HTTPStatus(e.response.status_code)
722726
if include_message_in_response:
723-
default_data = {"message": getattr(e, "description", code.phrase)}
727+
default_data = {"message": e.description or code.phrase}
724728
headers = e.get_response().headers
725729
elif self._default_error_handler:
726730
result = self._default_error_handler(e)

tests/test_errors.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@
66
from flask import Blueprint, abort
77
from flask.signals import got_request_exception
88

9-
from werkzeug.exceptions import HTTPException, BadRequest, NotFound, Aborter
9+
from werkzeug import Response
10+
from werkzeug.exceptions import (
11+
Aborter,
12+
BadRequest,
13+
HTTPException,
14+
NotFound,
15+
Unauthorized,
16+
)
1017
from werkzeug.http import quote_etag, unquote_etag
1118

1219
import flask_restx as restx
@@ -645,6 +652,16 @@ def test_handle_error_with_code(self, app):
645652
assert response.status_code == 500
646653
assert json.loads(response.data.decode()) == {"foo": "bar"}
647654

655+
def test_handle_error_http_exception_response_code_only(self, app):
656+
api = restx.Api(app)
657+
http_exception = HTTPException(response=Response(status=401))
658+
659+
response = api.handle_error(http_exception)
660+
assert response.status_code == 401
661+
assert json.loads(response.data.decode()) == {
662+
"message": "Unauthorized",
663+
}
664+
648665
def test_errorhandler_swagger_doc(self, app, client):
649666
api = restx.Api(app)
650667

0 commit comments

Comments
 (0)