Flask cannot raise HTTP exception after try catching Runtime error - python

When I try to raise a HTTP exception status code 400 it only prints the json error message on the browser but does not state HTTP/1.1 400 BAD REQUEST in the console like it is supposed to. The exception raising works for all other parts of my program but it doesn't work when I do it in a try-catch for a runtime error.
My exception handler is exactly this:
http://flask.pocoo.org/docs/0.11/patterns/apierrors/
my try-catch:
try:
// run some program
catch RuntimeError as e:
raise InvalidUsage(e.message, status_code=400)

You should use the abort function of flask, something like:
from flask import abort
#app.route("/some_route")
def some_route():
try:
# do something
except SomeException:
abort(400, "Some message")

Related

Don't Log 'Certificate did not match expected hostname' Error Messages

My web app requests several URLs and sometimes SSL certificate errors are raised. They are all third party URLs so I can't fix their errors and I prefer not to log them. Nevertheless, something is logging this by itself: 2017-08-05 00:22:49,496 ERROR -- : Certificate did not match expected hostname: www.improving-autonomy.org. Certificate: {'subjectAltName': [('DNS', '*.wordpress.com'), ('DNS', 'wordpress.com')], 'subject': ((('commonName', u'*.wordpress.com'),),)} Anyone knows how can I stop it? Please find my code bellow. Many thanks in advance!
try :
ua = UserAgent()
headers = {'Content-Type' : 'text/html', 'Accept-Encoding' : None, 'User-Agent' : ua.random}
response = requests.get(url, headers=headers, timeout=10)
except ssl.CertificateError as e :
pass
UPDATED -- :
It looks like requests module logs it (connection.py). Why it keeps logging if I'm already catching the same exception?
def _match_hostname(cert, asserted_hostname):
try:
match_hostname(cert, asserted_hostname)
except CertificateError as e:
log.error(
'Certificate did not match expected hostname: %s. '
'Certificate: %s', asserted_hostname, cert
)
# Add cert to exception and reraise so client code can inspect
# the cert when catching the exception, if they want to
e._peer_cert = cert
raise
Sure. You are catching the same exception, but what you are not seeing is where this is happening. Let's take a look at the snippet of what is happening here:
except CertificateError as e:
log.error(
'Certificate did not match expected hostname: %s. '
'Certificate: %s', asserted_hostname, cert
)
# Add cert to exception and reraise so client code can inspect
# the cert when catching the exception, if they want to
e._peer_cert = cert
raise
So, when the exception is first raised, that code catches the CertificateError, then it makes a log.error, assigns the cert as an attribute, per the comment in the code, then, a call to raise is made.
That empty raise call is now going to re-raise the last exception made, which is the CertificateError exception, and that is what you are catching. So the log call has already been made by that code, and your exception catching is being made from that specific raise call.
You can catch the exception and then print it's type:
except Exception as exc:
print exc, exc.message, exc.__class__
Then use this specific exception type in your code, which should work. Also you can add an else clause after the except statement, and put the logging code there. This code will be executed only if the try block executed successfully

Raise exception for error logs

I'm using a library that is logging an error. But I'd like it to raise an exception instead.
Is there quick way to have an exception raised instead of just an error being logged?
The library I'm using is cssutils, but for simplicity, suppose my code looks like:
from foo import do_something
do_something(x)
and suppose do_something will log an error if x was unacceptable input. Is there some quick hack that would cause an exception to be raised if do_something logs an error? Or is the only way to edit foo's source?
It's not clear if you want to still log the error, but you can try something like:
if error_is_true:
raise Exception("error message...")
With log:
try:
my_function()
except Exception:
logger.exception("error msg...")

Python requests - Exception Type: ConnectionError - try: except does not work

I am using a webservice to retrieve some data but sometimes the url is not working and my site is not loading. Do you know how I can handle the following exception so there is no problem with the site in case the webservice is not working?
Django Version: 1.3.1
Exception Type: ConnectionError
Exception Value:
HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url:
I used
try:
r = requests.get("http://test.com", timeout=0.001)
except requests.exceptions.RequestException as e: # This is the correct syntax
print e
sys.exit(1)
but nothing happens
You should not exit your worker instance sys.exit(1)
Furthermore you 're catching the wrong Error.
What you could do for for example is:
from requests.exceptions import ConnectionError
try:
r = requests.get("http://example.com", timeout=0.001)
except ConnectionError as e: # This is the correct syntax
print e
r = "No response"
In this case your program will continue, setting the value of r which usually saves the response to any default value

Python handle custom exception from java web service

I have a java web service and python client using suds. My server raises custom exceptions which I would like to handle in the python script. Is it possible to catch them or it always will be caught as suds.WebFault exception?
suds.WebFault has fault field that has information about fault.
except suds.WebFault, e:
print e.fault.faultstring
print e.document
You can have your program to analyze server custom exception from WebFault and create new exception class(es) for every specific server exception then catch suds.WebFault exception, read server exception details and raise your custom exception.
class MyException(suds.WebFault):
pass
def convertServerException(e):
if e.fault.faultstring == 'exception1':
return MyException()
#...add more exception handling cases here
#...
try:
#...make a WebService call
except suds.WebFault, e:
print e
print e.fault
raise convertServerException(e)

How to log exceptions in appengine?

try:
#do something that raises an exception...
except:
logging.error('Error Message')
I want more than just "Error Message" to show in the logs. I want to see the traceback, or at least what the exception was, in the logs as well. How do I do that?
Thanks!
logging.exception(msg[, *args])
Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler.
http://docs.python.org/library/logging.html#logging.exception
This is what I use to log the entire stack trace:
import traceback
try:
# your code
except:
stacktrace = traceback.format_exc()
logging.error("%s", stacktrace)
I think this should help you
import logging
try:
#exception code
except Exception as e:
logging.error(e)
You can set the logging details to Debug,Info,Warning,Error or Critical and set in your application. Debug would give you a lot of details.
import logging
logging.getLogger().setLevel(logging.DEBUG)
And you can get the logs of the particular filter in your appengine web console under /logs.

Categories

Resources