How to change Prometheus error message if token is invalid? - python

I have a python file called main.py and I am trying to make a Prometheus connection with a specific token. However, if the token is expired, instead of the error message printing out prometheus_api_client.exceptions.PrometheusApiClientException, how can I get the error message to print our like status_code: 500, reason: Invalid token using a try and except block.
Code:
#token="V0aksn-as9ckcnblqc6bi3ans9cj1nsk" #example, expired token
token ="c0ams7bnskd9dk1ndk7aKNYTVOVRBajs" #example, valid token
pc = PrometheusConnect(url = url, headers={"Authorization": "bearer {}".format(token)}, disable_ssl=True)
try:
#Not entirely sure what to put here and the except block
except:
I've tested out a couple code in the try and except blocks and could not get rid of the long error from Prometheus. Any suggestions?

How about putting your pc variable in try and PrometheusApiClientException for the exception. If that doesn't work, go to the source file and use whatever exception developers used while making authorization.

This is how you catch that exception in a try/except block
try:
# Interact with prometheus here
pass
except prometheus_api_client.exceptions.PrometheusApiClientException as e:
print('status_code: 500, reason: Invalid token')

Related

Python script stops at error instead of carrying on

I am using Telethon for a telegram bot.
I've got a list of phone numbers. If the phone number is valid then to run a script, if it is invalid I want it to check another number.
This is the part of script which is causing me issues.
from telethon.sync import TelegramClient
from telethon.errors.rpcerrorlist import PhoneNumberBannedError
api_id = xxx # Your api_id
api_hash = 'xxx' # Your api_hash
try:
c = TelegramClient('{number}', api_id, api_hash)
c.start(number)
print('Login successful')
c.disconnect()
break
except ValueError:
print('invalid number')
If the number is invalud then I would expect the script to print 'invalid number' and then carry on. Except it is throwing error 'telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)', then ending the script.
How can I carry on the script when this error is thrown?
Thanks
The exception you're catching is ValueError, but the error being thrown is telethon.errors.rpcerrorlist.PhoneNumberInvalidError.
So you need to catch that exception instead:
from telethon.errors.rpcerrorlist import PhoneNumberInvalidError
try:
# your code
except PhoneNumberInvalidError:
print('invalid number')
You can also combine error types if needed:
except (PhoneNumberInvalidError, ValueError):
# handle these types the same way
except TypeError:
# or add another 'except <type>' line to handle this error separately
This is especially useful when you're running a lot of code in your try and so a lot of different errors could occur.
Your last options is to catch every error using
try:
# code
except Exception:
print("exception!")
and while this might seem to be useful it will make debugging a lot harder as this will catch ANY error (which can easily hide unexpected errors) or it will handle them in the wrong way (you don't want to print 'invalid number' if it was actually a TypeError or KeyboardInterrupt for example).

Can't catch an exception, system just closes

I've implemented an orchestrator in python that makes some requisitions to an API. My problem is that sometimes it gets stucked in a request. To solve that I used the timeout parameter. Now I want to implement something so I can retry doing the requisition, but first I need to take care of the exception. For that I tried this:
uri = MS_MONITOR + "/api/monitor/advise/lawsuit/total/withProgressDaily"
try:
response = requests.get(uri, headers={"Correlation-Id": CORRELATION_ID}, timeout = 10)
except requests.exceptions.RequestException as e:
logging.info("[{}] [{}] {}".format("ERROR de Timeout", response.status_code, uri))
print("Deu timeout")
I put the timeout as 10 just to force it to happen, the problem is that it doesn't go into the exception part below, the cmd just closes. I've tried using this one too but it didn't work either:
except requests.exceptions.Timeout
If there's lack of information in my post please let me know so I'll provide it. Thank you!

Minio minio.error.SignatureDoesNotMatch thrown with try-except

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.

Error handling in python with ldap

I have this bit of code below, it is part of a python script iv been working on(piecing it together blocks at a time as learning curve). This bit binds to an ldap directory to query, so the rest of the script can to the queries.
When successful, it will print the below message in the block. When not successful it will throw an error- or at least i want to control the error.
If im not domain bound/vpn it will throw this message:
{'desc': "Can't contact LDAP server"}
if incorrect credentials :
Invalid credentials
nowhere in my script is it defined for the error message, how can i find where its fetching what to print that messsage- and possibly create or customize it?
(for what its worth i am using PyCharm)
try:
l = ldap.open(server)
l.simple_bind_s(user, pwd)
#if connection is successful print:
print "successfully bound to %s.\n" %server
l.protocol_version = ldap.VERSION3
except ldap.LDAPError, e:
print e
thanks
you can do something like this to provide a specific message for a specific exception.
try:
foo = 'hi'
bar = 'hello'
#do stuff
except ValueError:
raise ValueError("invalid credientials: {},{}".format(foo, bar))
so in your example it could become
except ldap.LDAPError:
raise ldap.LDAPError("invalid credientials: {},{}".format(user, pwd))
or if you literally just want to print it
except ldap.LDAPError:
print("invalid credientials: {},{}".format(user, pwd))

tweepy/ twitter api error type

I am using tweepy to make a twitter application.
When users tweet/update profile, etc, they will get some errors. I want to classify error and give user more information.
try:
tweet/update profile/ follow....
except tweepy.TweepError, e:
if tweepy.TweepError is "Account update failed: Description is too long (maximum is 160 characters)"
Do something
if tweepy.TweepError is "Failed to send request: Invalid request URL: http://api.twitter.com/1/account/update_profile.json?location=%E5%85%B5%E5%BA%A"
Do something
if tweepy.TweepError is "[{u'message': u'Over capacity', u'code': 130}]"
Do something
Is the only way to classify error is to compare e with string, for example, Account update failed: Description is too long (maximum is 160 characters)?
Right, it is the only way now. There is only one TweepError exception defined. It's raised throughout the app with different text.
Here's the relevant open issue on github. So there is a chance that it'll be improved in the future.

Categories