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})
Related
I am trying to handle not none or empty list exception while using boto3. I want to know is there any good way of pythonic code to write this.
buckets_list= None
try:
my_region = os.environ['AWS_REGION']
if my_region == 'us-east-1':
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error in connecting and listing bucket{}".format(err))
if buckets_list['Buckets']:
# Search for all buckets.
for bucket in buckets_list['Buckets']:
# my code follow to get other things...
else:
print("Buckets are empty in this region")
else:
print("Region not available")
raise Exception("Exception was thrown in Region")
except Exception as err:
logging.error('Exception was thrown %s' % err)
print("Error is {}".format(err))
raise err
Is this the right way or any suggestions would help.
You can use else block of the try except suite. It is useful for code that must be executed if the try clause does not raise an exception.
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error is {}".format(err))
else:
# This means the try block is succeeded, hence `buckets_list` variable is set.
for bucket in buckets_list['Buckets']:
# Do something with the bucket
One issue I am seeing from your code is that, if the list_buckets call is failed there is a chance to get NameError at the line if buckets_list['Buckets'] is not None:. Because buckets_list is undefined if the buckets_list call is failed. To understand this try to run the following snippet :)
try:
a = (1/0)
except Exception as e:
print(e)
print(a)
UPDATE
This is how I would implement this,
Use .get method to avoid KeyError
Use else block of the try except suite to specify the code must be executed if the try clause does not raise an exception.
my_region = os.environ.get('AWS_REGION')
if my_region == 'us-east-1':
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error in connecting and listing bucket{}".format(err))
else:
buckets_list = buckets_list['Buckets']
if not buckets_list:
print("Buckets are empty in this region")
else:
# Search for all buckets.
for bucket in buckets_list:
pass
# Do something with the bucket
else:
print("Region not available")
Your code is somewhat not detailed enough, at least the beginning of the function should have been shared. Anyway, did you consider:
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
print("buckets_list", buckets_list['Buckets'])
print("Error is {}".format(err))
if buckets_list['Buckets'] is not None: ##Here I am trying to check if buckets are empty
# Search for all buckets.
for bucket in buckets_list['Buckets']:
(your other codes)
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
I am using the python package for the minio server. I have the following piece of code that is used for a login:
from minio.error import [...], SignatureDoesNotMatch, [...]
def login(self):
try:
self.user = Minio(MINIO_CONFIG['MINIO_ENDPOINT'],
access_key=self.username,
secret_key=self.password,
secure=MINIO_CONFIG['MINIO_SECURE'])
return {"msg":"User is now logged in", "status": "OK"}
except SignatureDoesNotMatch as err:
return {"msg": err.message, "status":"F"}
except ResponseError as err:
return {'msg': err.message, 'status': "F"}
except InvalidAccessKeyId as err:
return {"msg": err.message, "status":"F"}
except InvalidArgument as err:
return {"msg": err.message, "status":"F"}
except InvalidArgumentError as err:
return {"msg": err.message, "status":"F"}
The issue I am facing is that even though I do have in the try-except the SignatureDoesNotMatch in case the credentials are not correct, it does not return me the msg it should but it throws an minio.error.SignatureDoesNotMatch instead. Why does that happen?
The error I get:
minio.error.SignatureDoesNotMatch: SignatureDoesNotMatch: message: The request signature we calculated does not match the signature you provided.
This seems fine, looking at the code, this will never run into an error on it's own, regardless of the credentials provided. It will only run into an error when it makes an API call, or when you invoke methods like list_buckets, list_objects etc using this self.user instance, from outside this block.
I think what you're trying to do is-- invoking methods like list_buckets etc from outside this encapsulation-- somewhere else not this part of the code, and then they produce this error and propagate them to the console. You cannot encapsulate the MinIO instance within try-catch and catch errors while you make use of stuff like self.user.list_buckets() from outside this try-catch block.
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))
I am new to python but I have experience with other languages like nodejs, java etc. I have a function in python defined like:
from flask import abort
def delete_contact(contact_id, api_key=None): # noqa: E501
print('delete contact ', contact_id)
session = Session()
try:
query = session.query(DBContact).filter(DBContact.id == contact_id)
print('delete count:', query.count())
if query.count() == 0:
print('return 404')
return abort(404, 'Not find record')
contact = query.one()
session.delete(contact)
session.commit()
return 'success'
except Exception as error:
print(error)
finally:
session.close()
print('xxxxx')
return abort(400, 'failed to delete contact ' + contact_id)
When execution this code I can see the output includes both return 404 and xxxxx. I don't understand why xxxxx get printed if the function returns in return abort(404, 'Not find record') already. In other language like java, javascript, if a function returns a value, the rest code should not execute except finally block. But the print('xxxxx') is outside finally block. Why is it executed?
abort(404, 'Not find record') raises a HTTPException, which is caught by your except block.
Therefore the return part of the return abort(404, 'Not find record') statement is never reached and instead of returning python will execute the except block followed by the finally block and then the statements after the try-except-finally statement.
The function then doesn't return either, because the line
return abort(400, 'failed to delete contact ' + contact_id)
raises another HTTPException, which will be propagated through the call stack.
The returns don't do anything.
If you want to propagate the HTTPException, but not other exceptions, you could do something like:
try:
...
except HTTPException:
raise
except Exception as error:
print(error)
finally:
...
...
This will raise the HTTPExceptions thrown by abort, but handle all other exceptions in the second except block, continuing the function afterwards.
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))