How to get status_code from an exception object

132 views Asked by At

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]>

2

There are 2 answers

0
0x00 On BEST ANSWER

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
3
SIGHUP On

exp_obj.response is None because you never got a response from the URL. That will happen, for example, if the hostname in the URL cannot be found. On the other hand, for example, if the hostname is valid but the sub-domain is invalid (resulting in HTTP 404) then you would have had a response that you can interrogate