Skip to content

Wrong status code and message on responses when handling HTTPExceptions #569

@lkk7

Description

@lkk7

Issue

There are two issues in handler_error method, in api.py.

  1. There might be a situation in Werkzeug where it raises an HTTPException(some_response). The code is in the response, but NOT in the HTTPException. Currently, Flask-RESTX checks gets the code only from the exception itself which will cause an error:
ValueError: None is not a valid HTTPStatus
  1. This code in the method is wrong:
default_data = {"message": getattr(e, "description", code.phrase)}

getattr returns the default value (code.phrase) only if e.description doesn't exist, which will never happen. It's always set to None by default, so it exists.

The final result of these problems is that

  1. You get an error when an HTTPException is raised without a status code (which is expected), even if its response has a status code.
  2. If you fix that error and go further, you'll receive a null message instead of the default one.

Reproduction Steps

  1. Add and run the test in tests/test_errors.py. Conveniently it catches both problems.
    # ... Add this import
    from werkzeug import Response
    # ...

    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) # <-- Will fail with "ValueError: None is not a valid HTTPStatus"
        assert response.status_code == 401 # <-- Doesn't get there, but when we fix the status code it will go further
        assert json.loads(response.data.decode()) == {
            "message": "Unauthorized",   # <-- Will fail, message is None
        }

Expected Behavior

The code and message should be set as expected (401, "Unauthorized")

Actual Behavior

Message is set to None, but it doesn't even happen because before that, we get:
ValueError: None is not a valid HTTPStatus due to code being None.

Environment

  • Python version 3.11
  • Flask version (2.3.3 as the newer ones don't work for Flask-RESTX, but the version doesn't matter)
  • Flask-RESTX version (1.1.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions