Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Status code 500 not treated as exception

Making a request to the server, as in code below, I've got status code 500, which was not caught as an exception. The output was "500", but I need for all 500 codes to result in sys.exit(). Does requests.exceptions.RequestException not treat 500 as an exception or is it something else? The requests module docs http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions are not very clear on what falls under this class. How do I make sure that all 500 codes result in sys.exit()?

import requests
import json
import sys

url = http://www.XXXXXXXX.com
headers = {'user':'me'}
try:
    r = requests.post(url, headers=headers)
    status = r.status_code
    response = json.dumps(r.json(), sort_keys=True, separators=(',', ': '))
    print status
except requests.exceptions.RequestException as e:
    print "- ERROR - Web service exception, msg = {}".format(e)
    if r.status_code < 500:
        print r.status_code
    else:
        sys.exit(-1)
like image 625
postoronnim Avatar asked Feb 21 '17 23:02

postoronnim


People also ask

What does a status code of 500 mean?

The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request.

How do I force a 500 error?

As for the error page, if you just want to view the page, you can navigate to it directly... if you want to force a 500 error to happen, just change the db password in your . env to something that doesn't work. That specific problem/error was due to an incorrect path set in php. ini.

Is error 500 my fault?

If you try to visit a website and see a “500 Internal Server Error” message, it means something has gone wrong with the website. This isn't a problem with your browser, your computer, or your internet connection. It's a problem with the site you're trying to visit.


2 Answers

A status code 500 is not an exception. There was a server error when processing the request and the server returned a 500; more of a problem with the server than the request.

You can therefore do away with the try-except:

r = requests.post(url, headers=headers)
status = r.status_code
response = json.dumps(r.json(), sort_keys=True, separators=(',', ': '))

if str(status).startswith('5'):
    ...
like image 88
Moses Koledoye Avatar answered Sep 28 '22 09:09

Moses Koledoye


If you want a successful request, but "non-OK" response to raise an error, call response.raise_for_status(). You can then catch that error and handle it appropriately. It will raise a requests.exceptions.HTTPError that has the response object hung onto the error.

like image 38
Nick T Avatar answered Sep 28 '22 08:09

Nick T