diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 175ecdc1..2f98370b 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -36,6 +36,7 @@ Bug Fixes * Fixing werkzeug 3 deprecated version import. Import is replaced by new style version check with importlib (#573) [Ryu-CZ] * Fixing flask 3.0+ compatibility of `ModuleNotFoundError: No module named 'flask.scaffold'` Import error. (#567) [Ryu-CZ] + * Fix wrong status code and message on responses when handling `HTTPExceptions` (#569) [lkk7] .. _section-1.2.0: diff --git a/flask_restx/api.py b/flask_restx/api.py index 131697e4..6c348727 100644 --- a/flask_restx/api.py +++ b/flask_restx/api.py @@ -718,9 +718,13 @@ def handle_error(self, e): got_request_exception.send(current_app._get_current_object(), exception=e) if isinstance(e, HTTPException): - code = HTTPStatus(e.code) + code = None + if e.code is not None: + code = HTTPStatus(e.code) + elif e.response is not None: + code = HTTPStatus(e.response.status_code) if include_message_in_response: - default_data = {"message": getattr(e, "description", code.phrase)} + default_data = {"message": e.description or code.phrase} headers = e.get_response().headers elif self._default_error_handler: result = self._default_error_handler(e) diff --git a/tests/test_errors.py b/tests/test_errors.py index 3fa9e0ea..28fe5110 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -6,7 +6,14 @@ from flask import Blueprint, abort from flask.signals import got_request_exception -from werkzeug.exceptions import HTTPException, BadRequest, NotFound, Aborter +from werkzeug import Response +from werkzeug.exceptions import ( + Aborter, + BadRequest, + HTTPException, + NotFound, + Unauthorized, +) from werkzeug.http import quote_etag, unquote_etag import flask_restx as restx @@ -645,6 +652,16 @@ def test_handle_error_with_code(self, app): assert response.status_code == 500 assert json.loads(response.data.decode()) == {"foo": "bar"} + def test_handle_error_http_exception_response_code_only(self, app): + api = restx.Api(app) + http_exception = HTTPException(response=Response(status=401)) + + response = api.handle_error(http_exception) + assert response.status_code == 401 + assert json.loads(response.data.decode()) == { + "message": "Unauthorized", + } + def test_errorhandler_swagger_doc(self, app, client): api = restx.Api(app)