The Exception
class is the base class of all user-defined exceptions (it a recommandation).
This class inherits the BaseException
which has a args
attributes.
This attribute is defined as follow:
args
The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
If the error message is in args[0]
, you can try:
try:
resp = requests.get(url)
except Exception as e:
data['error'] = e.args[0]
Your are not speaking of the standard exception, because print (e.strerror)
should raise AttributeError
.
For your answer, you ought to consider the answer of this qestion: Correct way to try/except using Python requests module?
All Requests exceptions inherit requests.exceptions.RequestException
, which inherits IOError
.
About IOError
, the documentation says:
exception EnvironmentError
The base class for exceptions that can occur outside the Python system: IOError, OSError. When exceptions of this type are created with a 2-tuple, the first item is available on the instance’s errno attribute (it is assumed to be an error number), and the second item is available on the strerror attribute (it is usually the associated error message). The tuple itself is also available on the args attribute.
But RequestException
doesn't seems to be created with a 2-tuple, so strerror is None
.
EDIT: add some examples:
If you have HTTPError
, the original message is in args[0]
. See this sample of code in requests.models.Response.raise_for_status
:
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
If you have ConnectionError
, the args[0]
contains the original error. See this sample in requests.adapters.HTTPAdapter.send
:
except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)
It’s the same for ProxyError
, SSLError
, Timeout
: args[0]
contains the original error.
...
Browse the source code in the GitHub repo.
One solution could be:
try:
resp = requests.get(url)
except requests.exceptions.HTTPError as e:
data['error'] = e.args[0]
except requests.exceptions.RequestException as e:
cause = e.args[0]
data['error'] = str(cause.args[0])