Search code examples
pythonexceptionhttprequesthttpresponsehttp-status-codes

How to get status_code from an exception object


In my code I have a get request as:

response = requests.get(url)

For invalid status code ie non 2xx an exception is raised,

exp_obj = RequestException(response)

Now I want to get the status code from this exception object exp_obj

I tried exp_obj.response.status_code but I am getting AttributeError: 'NoneType' object has no attribute 'status_code'

If I print exp_obj it is same as response object ie <Response [500]>


Solution

  • This feels like an XY problem. But looking at what you are trying to do. You need to check the way requests.exceptions.RequestException() works.

    class RequestException(IOError):
        def __init__(self, *args, **kwargs):
            """Initialize RequestException with `request` and `response` objects."""
            response = kwargs.pop("response", None)
            self.response = response
            self.request = kwargs.pop("request", None)
            if response is not None and not self.request and hasattr(response, "request"):
                self.request = self.response.request
            super().__init__(*args, **kwargs)
    

    For your exp_obj to contain the response, you have to create the RequestException using named arguments (**kwargs). exp_obj = RequestException(response=response)

    In your case you should be doing this.

    >>> response = requests.get("https://httpstat.us/404")
    >>> exp_obj = RequestException(response=response)
    >>> vars(exp_obj))
    {'response': <Response [404]>, 'request': <PreparedRequest [GET]>}
    >>> exp_obj.response.status_code
    404