TweepError attribute error when using Tweepy - python

I am getting an AttributeError: module 'tweepy' has no attribute 'TweepError'. Here is my relevant code in Python:
except tweepy.TweepError as e:
msg = 'Query failed when max_id equaled {0}: {1}'.format(max_id, e)
logging.error(msg)
my other code with tweepy is working so I'm sure I've installed it correctly, and it seems that tweep error is included in the current documentation.

except tweepy.errors.TweepyException as e:

The correct exception is tweepy.errors.TweepError, so change that line to:
except tweepy.errors.TweepError as e:
in older versions of Tweepy, it was previously:
except tweepy.error.TweepError as e:

I tried solutions above but as of 24th of May, this one works for me:
except AttributeError:

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))

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!

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

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))

check ftplib response code

I have a python application that's accessing an ftp server. There are several error cases I'd like to catch in a fashion similar to httplib2:
try:
urllib2.urlopen("http://google.com")
except urllib2.HTTPError, e:
if e.code == 304:
#do 304 stuff
if e.code == 404:
#do 404 stuff
else:
pass
Does a a construct like this exist in ftplib.err_perm? I know that could return a code of 500-599 according to the docs but I don't see anything in the docs about how to access that value. Did I miss something?
You can access error reponse string using <exception_obj>.args[0]. It contains strings like '550 /no-such-dir: No such file or directory'.
To get error code (only leading three chracters), use <exception_obj>.args[0][:3].
For example:
import ftplib
ftp = ftplib.FTP('ftp.hq.nasa.gov')
ftp.login('anonymous', 'user#example.com')
try:
ftp.cwd('/no-such-dir')
except ftplib.error_perm as e:
print('Error {}'.format(e.args[0][:3]))
finally:
ftp.quit()

Categories