If i have some bad authorization data (for example wrong password) SUDS rises exception (400, u'Bad Request') from which i cant get anything, but in teh log is response, which contains data that password is wrong, but how to get this response? I tried like this:
except Exception as e:
print str(e)
print self._client.last_received()
It prints:
(400, u'Bad Request')
None
But in log there is long xml which contains <SOAP-ENV:Reason><SOAP-ENV:Text xml:lang="en">Sender not authorized</SOAP-ENV:Text></SOAP-ENV:Reason>
I am pulling this out of a comment and into an answer because of the code block.
import suds.client
try:
auth_url = "https://url.to.my.service/authenticator?wsdl"
auth_client = suds.client.Client(auth_url)
cookie = auth_client.service.authenticate(user,password)
except Exception as e:
print str(e)
print auth_client.last_received()
Using this code, I receive the appropriate response from my service if I pass an invalid password:
Server raised fault: 'error.pwd.incorrect'
None
And an appropriate response if I pass an invalid user id:
Server raised fault: 'error.uid.missing'
None
Something you may want to consider doing, is changing your except statement to catch suds.WebFault instead of the generic exception. There may be something else that is occurring and triggering your exception block.
One other thing that may help with your issue, is to pass faults=True in your Client() call.
The Client can be configured to throw web faults as WebFault or to
return a tuple (, )
The code I posted above would look like this:
auth_client = suds.client.Client(auth_url, faults=True)
Related
I am using the following approach for handling Twilio exceptions in Python:
try:
#code for sending the sms
print(message.sid)
except TwilioRestException as e:
print(e)
This allows me to send sms and Exceptions are handled by Python.
Now I need to "return" the exceptions codes in order to process them, let's say, give user a message depending on the exception.
How can I achieve that?
If raising exception is not an option you could simply add return under except block.
def func():
# your logic
try:
#code for sending the sms
print(message.sid)
except TwilioRestException as e:
print(e)
return e.code # or whetever attribute e has for it...
By default function will return None if everything goes right. In client code it will be like
err = func()
if err:
# sms wasn't sent, action required
I am learning how to use Zeep as my soap client. I am able to connect to a WSDL and view services, however, I am stuck on how to catch all possible exceptions. I am only able to catch KeyError. I want to be able to catch a few more:
Basically something similar to the below http client example:
except (http.client.HTTPException, ValueError, KeyError, AttributeError) as e
I would want to use try.....except
try:
session = Session()
session.auth = HttpNtlmAuth(username, password)
request_data = {
}
client = Client(wsdl, transport=Transport(session=session))
response = client.service.GetPendingBills(**request_data)
billobj = json.loads(response)
print(billobj)
bills = (len(billobj["Bills"]))
except KeyError as e:
bills = 0
Maybe this is too late, but you can import zeep.exceptions and handle all kinds of exceptions that you have that way. You just need to check the exception and catch it as you have demonstrated above.
Solution is shown in this documentation
I decided to import requests and handle the exceptions as indicated below:
except (requests.exceptions.HTTPError, KeyError, TimeoutError) as e
Thanks
I've been given some web scraping code on Python and now need to write some code so that if there is an error, it will notify someone by email. I have found this code online:
def send_email():
to = request.form.get('to')
if not to:
return ('Please provide an email address in the "to" query string '
'parameter.'), 400
sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
to_email = mail.Email(to)
from_email = mail.Email(SENDGRID_SENDER)
subject = 'This is a test email'
content = mail.Content('text/plain', 'Example message.')
message = mail.Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=message.get())
if response.status_code != 202:
return 'An error occurred: {}'.format(response.body), 500
return 'Email sent.'
Is this the kind of thing that I should use? If not, what is the best way to go about this problem?
Thanks in advance.
What I meant:
try:
# Web scrapping code
except requests.packages.urllib3.exceptions.MaxRetryError as e:
print repr(e)
send_email()
OR
use except without specifying for passive handling.
try:
# Web scrapping code
except:
send_email()
BUT:
From the PEP-8 Style Guide for Python:
When catching exceptions, mention specific exceptions whenever
possible instead of using a bare except: clause.
A bare except: clause will catch SystemExit and KeyboardInterrupt
exceptions, making it harder to interrupt a program with Control-C,
and can disguise other problems. If you want to catch all exceptions
that signal program errors, use except Exception: (bare except is
equivalent to except BaseException:).
A good rule of thumb is to limit use of bare 'except' clauses to two
cases:
If the exception handler will be printing out or logging the
traceback; at least the user will be aware that an error has occurred.
If the code needs to do some cleanup work, but then lets the exception
propagate upwards with raise. try...finally can be a better way to
handle this case.
When I have two Python exceptions that are the same exception class but a different error message, how do I catch them separately?
For specific use-case:
I'm using the Facepy library to hit the Facebook Graph API. When the API returns an error that isn't Oauth related, Facepy raises a facepy.exceptions.FacebookError and passes the error message given by the Facebook API.
I'm consistently hitting two different errors that I'd like to treat differently and the only way to parse them is the error message, but I can't figure out how to write my except clause--here it is in pseudo-code:
try:
#api query
except facepy.exceptions.OAuthError and error_message = 'object does not exist':
# do something
except facepy.exceptions.OAuthError and error_message = 'Hit API rate limit':
# do something else
How do I write these except clauses to trigger off both the exception and the error message?
Assuming the Exception's error message is in the error_message attribute (it may be something else — look at the Exception's __dict__ or source to find out):
try:
#api query
except facepy.exceptions.OAuthError as e:
if e.error_message == "object does not exist":
print "Do X"
elif e.error_message == "Hit API rate limit":
print "Do Y"
else:
raise
facepy's OAuthError derives from FacebookError and that has message attribute. https://github.com/jgorset/facepy/blob/master/facepy/exceptions.py#L8. So, you can use if condition with the message like this
try:
#api query
except facepy.exceptions.OAuthError as error:
if 'object does not exist' == error.message:
# do something
elif 'Hit API rate limit' == error.message:
# do something else
else:
raise
I am trying to handle jira-python exception but my try, except does not seem to catch it. I also need to add more lines in order to be able to post this. So there they are, the lines.
try:
new_issue = jira.create_issue(fields=issue_dict)
stdout.write(str(new_issue.id))
except jira.exceptions.JIRAError:
stdout.write("JIRAError")
exit(1)
Here is the code that raises the exception:
import json
class JIRAError(Exception):
"""General error raised for all problems in operation of the client."""
def __init__(self, status_code=None, text=None, url=None):
self.status_code = status_code
self.text = text
self.url = url
def __str__(self):
if self.text:
return 'HTTP {0}: "{1}"\n{2}'.format(self.status_code, self.text, self.url)
else:
return 'HTTP {0}: {1}'.format(self.status_code, self.url)
def raise_on_error(r):
if r.status_code >= 400:
error = ''
if r.text:
try:
response = json.loads(r.text)
if 'message' in response:
# JIRA 5.1 errors
error = response['message']
elif 'errorMessages' in response and len(response['errorMessages']) > 0:
# JIRA 5.0.x error messages sometimes come wrapped in this array
# Sometimes this is present but empty
errorMessages = response['errorMessages']
if isinstance(errorMessages, (list, tuple)):
error = errorMessages[0]
else:
error = errorMessages
elif 'errors' in response and len(response['errors']) > 0:
# JIRA 6.x error messages are found in this array.
error = response['errors']
else:
error = r.text
except ValueError:
error = r.text
raise JIRAError(r.status_code, error, r.url)
I know I'm not answering the question, but I feel I need to warn people that could get confused by that code (as I did)...
Maybe you are trying to write your own version of jira-python or it's an old version?
In any case, here the link to the jira-python code for the JIRAError class
and here the list of codes
to catch the exception from that package I use the below code
from jira import JIRA, JIRAError
try:
...
except JIRAError as e:
print e.status_code, e.text
Maybe it is obvious and that's why you don't have it in your code paste, just in case, you do have
from jira.exceptions import JIRAError
somewhere in your code right?
Don't have enough reputation for comments so I'll add it answer for #arynhard:
I found the docs very light in particular in terms of example, you might find the scripts in this repo useful since they're all leveraging jira-python in someway or another.
https://github.com/eucalyptus/jira-scripts/
I might be wrong, but looks like you're catching jira.exceptions.JIRAError, while raising JIRAError - those are different types. You need to either remove "jira.exceptions." part from your except statement, or raise jira.exceptions.JIRAError instead.
Ok it's a very old one but I faced the same problem and this page is still showing up.
Here is how I trap the Exception, I used the Exception object.
try:
issue = jira.issue('jira-1')
except Exception as e:
if 'EXIST' in e.text:
print 'The issue does not exist'
exit(1)
regards