Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading