python requests: how can I get the "exception code" - python

I am using "requests (2.5.1)" .now I want to catch the exception and return an dict with some exception message,the dict I will return is as following:
{
"status_code": 61, # exception code,
"msg": "error msg",
}
but now I can't get the error status_code and error message,I try to use
try:
.....
except requests.exceptions.ConnectionError as e:
response={
u'status_code':4040,
u'errno': e.errno,
u'message': (e.message.reason),
u'strerror': e.strerror,
u'response':e.response,
}
but it's too redundancy,how can I get the error message simplicity?anyone can give some idea?

try:
#the codes that you want to catch errors goes here
except:
print ("an error occured.")
This going to catch all errors, but better you define the errors instead of catching all of them and printing special sentences for errors.Like;
try:
#the codes that you want to catch errors goes here
except SyntaxError:
print ("SyntaxError occured.")
except ValueError:
print ("ValueError occured.")
except:
print ("another error occured.")
Or;
try:
#the codes that you want to catch errors goes here
except Exception as t:
print ("{} occured.".format(t))

Related

How to catch an exception message in python?

I want something of the form
try:
# code
except *, error_message:
print(error_message)
i.e I want to have a generic except block that catches all types of exceptions and prints an error message. Eg. "ZeroDivisionError: division by zero". Is it possible in python?
If I do the following I can catch all exceptions, but I won't get the error message.
try:
# code
except:
print("Exception occurred")
Try this:
except Exception as e:
print(str(e))
This will allow you to retrieve the message of any exception derived from the Exception base class:
try:
raise Exception('An error has occurred.')
except Exception as ex:
print(str(ex))

Simple way to re-run try block if a specific exception occurs?

I'm using Python 3.7 and Django and trying to figure out how to rerun a try block if a specific exception is thrown. I have
for article in all_articles:
try:
self.save_article_stats(article)
except urllib2.HTTPError as err:
if err.code == 503:
print("Got 503 error when looking for stats on " + url)
else:
raise
What I would like is if a 503 errors occurs, for the section in the "try" to be re-run, a maximum of three times. Is there a simple way to do this in Python?
You can turn this in a for loop, and break in case the try block was successful:
for article in all_articles:
for __ in range(3):
try:
self.save_article_stats(article)
break
except urllib2.HTTPError as err:
if err.code == 503:
print("Got 503 error when looking for stats on " + url)
else:
raise
In case the error code is not 503, then the error will reraise, and the control flow will exit the for loops.

try and catch in inserting python?

I am just thinking how to do try and catch with it, what i am trying to achieve is like this:
try:
dbSession.execute(
"INSERT INTO users (username, email, password) VALUES (:username, :email, :password)",
{"username": reg_form.username.data, "email": reg_form.email.data, "password": hashed_password}
)
dbSession.commit()
return jsonify({'success': 'OK'})
except e:
return jsonify({'error': e})
in js, error is passed automatically, but in python i see samples like this,
except ValueError:
is it possible to pass the e automatically in python?
you do except ValueError: if you want to differentiate your catches based on the Error you are getting. Here, you catch a ValueError if you expect an int, but get a str for example.
But you can just keep it generic if you want by doing except:.
As pointed out in Maor Refaeli's comment, you can name your exception as e if you like.
you can read more about python exceptions on this link right here.
You need to catch that Exception First. So here you need to catch the exception ValueError and you can write the error return message to the variable e.
except ValueError as e:
return jsonify({'error': e})
Which is what this code does. Or if you donot want to catch a specific Exception you could just.
except Exception as e:
return jsonify({'error': e})
You can print or return the Value error as below:
except ValueError as err:
print(f"Failed - {err}")
OR
except ValueError as err:
return jsonify({'error': err})

Client Error Exception's message in try except case

Hey I know I can do try except to resolve ClientError warning but is there any way that exception could be more precise meaning instead of except ClientError: Can I do except InvalidPermission.Duplicate:
This is the complete output I am getting without applying any exceptions:
botocore.exceptions.ClientError: An error occurred (InvalidPermission.Duplicate)
You can get error code like this -
using this-
try:
boto3_api_operation()
except ClientError as e:
code = e.response["Error"]["Code"]
print(code)
#O/p - InvalidPermission.Duplicate
You can read AWS Error Codes Documentation
Let me know,if it helps!

urllib request fails when page takes too long to respond

I have a simple function (in python 3) to take a url and attempt to resolve it: printing an error code if there is one (e.g. 404) or resolve one of the shortened urls to its full url. My urls are in one column of a csv files and the output is saved in the next column. The problem arises where the program encounters a url where the server takes too long to respond- the program just crashes. Is there a simple way to force urllib to print an error code if the server is taking too long. I looked into Timeout on a function call but that looks a little too complicated as i am just starting out. Any suggestions?
i.e. (COL A) shorturl (COL B) http://deals.ebay.com/500276625
def urlparse(urlColumnElem):
try:
conn = urllib.request.urlopen(urlColumnElem)
except urllib.error.HTTPError as e:
return (e.code)
except urllib.error.URLError as e:
return ('URL_Error')
else:
redirect=conn.geturl()
#check redirect
if(redirect == urlColumnElem):
#print ("same: ")
#print(redirect)
return (redirect)
else:
#print("Not the same url ")
return(redirect)
EDIT: if anyone gets the http.client.disconnected error (like me), see this question/answer http.client.RemoteDisconnected error while reading/parsing a list of URL's
Have a look at the docs:
urllib.request.urlopen(url, data=None[, timeout])
The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used).
You can set a realistic timeout (in seconds) for your process:
conn = urllib.request.urlopen(urlColumnElem, timeout=realistic_timeout_in_seconds)
and in order for your code to stop crushing, move everything inside the try except block:
import socket
def urlparse(urlColumnElem):
try:
conn = urllib.request.urlopen(
urlColumnElem,
timeout=realistic_timeout_in_seconds
)
redirect=conn.geturl()
#check redirect
if(redirect == urlColumnElem):
#print ("same: ")
#print(redirect)
return (redirect)
else:
#print("Not the same url ")
return(redirect)
except urllib.error.HTTPError as e:
return (e.code)
except urllib.error.URLError as e:
return ('URL_Error')
except socket.timeout as e:
return ('Connection timeout')
Now if a timeout occurs, you will catch the exception and the program will not crush.
Good luck :)
First, there is a timeout parameter than can be used to control the time allowed for urlopen. Next an timeout in urlopen should just throw an exception, more precisely a socket.timeout. If you do not want it to abort the program, you just have to catch it:
def urlparse(urlColumnElem, timeout=5): # allow 5 seconds by default
try:
conn = urllib.request.urlopen(urlColumnElem, timeout = timeout)
except urllib.error.HTTPError as e:
return (e.code)
except urllib.error.URLError as e:
return ('URL_Error')
except socket.timeout:
return ('Timeout')
else:
...

Categories