Client Error Exception's message in try except case - python

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!

Related

TweepError attribute error when using Tweepy

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:

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

Error handling Telegram bot

I am trying to avoid a telegram error. This error occurs when a message is not modified:
telegram.error.BadRequest: Message is not modified
I would like to make a function to print a message when this error occurs instead the original error message telegram prints. I have tried something like this but does not work:
def error_callback(bot, update, error):
try:
raise error
except BadRequest:
# handle malformed requests - read more below!
print('Same message')
First of all, if there are no evident bugs, this error could be happen if a user if clicking too fast on a button. In this case it can be easily ignored.
Assuming you are using python-telegram-bot library looking at your code, you can follow 2 approaches:
1. Ignore the error globally:
def error(bot, update, error):
if not (error.message == "Message is not modified"):
logger.warning('Update "%s" caused error "%s"' % (update, error))
but you will still receive on the console:
2017-11-03 17:16:41,405 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update
the only thing you can do is to disable that string for any error of any type doing this:
updater.dispatcher.logger.addFilter((lambda s: not s.msg.endswith('A TelegramError was raised while processing the Update')))
in your main(). credits
2. Ignore the error in the method you are calling:
You can ignore the error in the method you are calling doing:
try:
# the method causing the error
except TelegramError as e:
if str(e) != "Message is not modified": print(e)
This second approach will ignore the error completely on the console without modifying the error callback function, but you have to use it in every single method causing that exception.
Printing 'text' instead of ignoring:
i suggest you to ignore the error, but if you want to print a string as you said: you can very easily modify those 2 approaches to print the string.
Example for the first approach:
def error(bot, update, error):
if error.message == "Message is not modified":
# print your string
return
logger.warning('Update "%s" caused error "%s"' % (update, error))
Example of the second approach:
try:
# the method causing the error
except TelegramError as e:
if str(e) == "Message is not modified": print(your_string)

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

Categories