状态代码500不被视为异常

时间:2017-02-21 23:17:27

标签: python http error-handling python-requests

向服务器发出请求,如下面的代码所示,我已获得状态代码500,但未将其作为例外情况捕获。输出是" 500",但我需要所有500个代码才能生成sys.exit()。 requests.exceptions.RequestException不会将500视为异常,还是其他什么?请求模块文档http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions不清楚此类的内容。如何确保所有500个代码都生成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)

3 个答案:

答案 0 :(得分:5)

状态代码500也不例外。处理请求时服务器出错,服务器返回500;服务器的问题多于请求。

因此,您可以取消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'):
    ...

答案 1 :(得分:3)

如果您想要成功请求,但“不正常”响应会引发错误call response.raise_for_status()。然后,您可以捕获该错误并适当地处理它。它会引发一个var commandText = "insert into MyTable ([a ton of variables]) values(:A,:B,..........)"; using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); using (OracleCommand command = new OracleCommand(commandText, connection)) { for (the ton of variables there are to insert whose values are in a collection) command.Parameters.Add(theVariableName, theVariableValue); } command.ExecuteNonQuery(); } requests.exceptions.HTTPError对象挂在错误上。

答案 2 :(得分:2)

来自Requests documentation

  

如果我们发出错误请求(4XX客户端错误或5XX服务器错误   响应),我们可以用Response.raise_for_status():

来提高它
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error
     

所以,使用

r = requests.post(url, headers=headers)
try:
    r.raise_for_status()
except requests.exceptions.HTTPError:
    # Gave a 500 or 404
else:
    # Move on with your life! Yay!