Hook into exceptions framework in CherryPy - cherrypy

I'm looking for a method to hook into the exceptions framework in CherryPy. The reason for this is to be able to do custom logging with any exceptions raised by the application. For example:
from cherrypy.exception import exception_hook, continue_to_raise
#exception_hook
def custom_exception_hook(exception):
custom_logger(exception)
continue_to_raise()
I know this is quite an abstract example, but basically I would like to catch all exception objects, forward them to something like Sentry and then continue with CherryPy's usual handler. A bit like:
try:
something()
except Exception as e:
custom_logger(e)
raise
I'm aware I could do this per error, but I'd like to do it in an efficient way.
Thanks

Related

What does `napi_throw_error` do when called from an asynchronous N-API addon's `napi_async_complete_callback`?

I recently completed making an asynchronous version for all the functions in a pure C API, wrapped with N-API to work with JS/TS as a nodejs addon.
The last problem I had to fix was making sure that C POSIX-style errors (ie, returned integer codes) were transferred correctly to the JS at the end of a worker's execution (with the corresponding string, for which we have both an enum of exceptions, and a list of error messages).
When thrown with napi_throw_error (as I did for the synchronous version of all our calls), within the napi_async_complete_callback, these exceptions were never caught at the JS level (I suppose it was because it was within a different async context; I saw online people having a similar problem with ajax). Instead, I opted to just construct my errors as napi_value types, and return these via napi_reject_deferred. This seemed to have the desired effect, of being caught properly when doing a try { await My_NapiWrapper_XYZ() } catch (ex) { ... }.
So I don't really have a problem to fix, but I AM intrigued. These napi_throw_error thrown errors do probably go somewhere. Though I have no idea where. Where should one look to catch an error thrown with napi_throw_error from a napi_async_complete_callback ? Can you give a code example ?
No, they don't go anywhere. It is a bug that I just opened with them:
https://github.com/nodejs/node/issues/41377
There is a general problem with handling exceptions in asynchronous callbacks. Normally, they cannot be catched and should lead to program termination but Node's developers have decided to try to keep it running when they can.

Python: chain an exception to a warning

I want to handle certain exceptions by catching the exception and issuing a warning. When the warning is displayed (e.g. on stderr or in a log file, I use the logging module for that) I want it to display the stack trace of the warning followed by "caused by" plus the stack trace of the original exception.
If I were to raise another exception I would use the from keyword (assume XException, YException are custom exception classes derived from Exception and YWarning is derived from the Warning class):
def do_x():
riase XException("Failed to do X")
def do_y():
try:
# do other things
do_x()
# maybe do some more things
except XException as x_exc:
raise YException("Failed to do Y") from x_exc
But in my case, if doing X fails, it's not such a big deal and I can continue to do Y. I want to issue a warning though.
from warnings import warn
def do_x():
raise XException("Failed to do X")
def do_y():
try:
# do other things
do_x() # if this fails, we can live with it
except XException as x_exc:
warn(YWarning("Things went not so smooth with doing Y", cause=x_exc))
Here I made up the cause= optional argument, so what I'd like to know is how do I instantiate any Exception subclass (which includes Warning and its subclasses) and specify the cause.
So while writing this question I came up with a possible answer.
ywarn = YWarning("Things went not so smooth with doing Y")
ywarn.__cause__ = x_exc
warn(ywarn)
It turns out, according to PEP 3134, that from does exactly that.
One could even actually implement the imaginary cause= optional argument. After all, the YWarning is a custom subclass.
class YWarning(Warning):
def __init__(self, msg, cause=None):
self.__cause__ = cause

What is the preferred way to call synchronous code from async routes in Sanic?

I'm researching Sanic as we're looking for alternatives to our flask-based rest services. I'm intriguied by the async nature of sanic, but I know that we'll bump into a lot of code that simply won't support async (we use a ton of boto3 and also some ORMs on top of DynamoDB for example, none of which support awaiting).
So: I need to find the cleanest way of being able to run synchronous code inside an async framework like Sanic. In python 3.7 there's the asyncio.create_task call which I'm finding interesting.
Wondering if this would be a possible way to go:
main.py:
#default boilerplate sanic code excluded for brevity
from app_logic import AppLogic
#app.route("/")
async def test(request):
task = await asyncio.create_task(AppLogic.sync_request('https://stuff.com'))
return json({"hello": "world", 'status_code': task.status_code})
app_logic.py:
import requests
class AppLogic(object):
#staticmethod
async def sync_request(url='https://myurl.com'):
#Some non-async library/code thingy
print('requesting the thing')
return requests.get(url)
This seems to work, and the the returned task object is a regular requests response.
However, I have no idea if this is "safe" - eg I'm not sure how I can investigate the event loop and verify that it's not blocking in any way. I'm sure there's also other reasons for this approach being completely dumb, so lay them on me :-)

unrecognised exception in windows C++ code

We have a number of sections of code in the format:
try
{
// code
}
catch(std::exception &e)
{
// log exception
}
catch(...)
{
// log unknown exception.
}
Every so often, the unknown exception code triggers, and logs an unknown exception.
I always thought that all exceptions were meant to derive from std::exception, and thus catching std::exception would catch all exceptions.
Is there some other exception that I should be catching?
If my code ends up in the unknown exception handler, is there any way that I can find out what exception was actually caught?
edit
We managed to locate the cause of the problem- despite saying that they had, the customer had not installed .NET 3.5, which our code depends on, and the system fell over when trying to use the XML parser.
Is there some other exception that I should be catching?
This depends on your code. Libraries you call can throw exceptions not derived from std::exception, examples are MFC's CException or Microsoft's _com_error. Also, an access violation might be catched by catch(...), which is the reason why I would not use catch(...) in my code - it's just to broad for me.
2.If my code ends up in the unknown exception handler, is there any way that I can find out what exception was actually caught?
You can run your code in the debugger and configure the debugger to break your program when the exception is thrown (first chance). Then you know exactly which line of code triggers the exception and should be able to see what exactly is thrown.

Server.Transfer and System.Threading.ThreadAbortException

See http://support.microsoft.com/kb/312629/EN-US/
I am using reponse.direct in my app as well and I am not getting the exception. The workaround that the knowledge base article suggests (Server.Execute) does not work for me. I am getting lots of javascript exceptions from the Ajax Toolkit on the target page if I use Server.Execute, and I did not dig into the cause.
My question - what arguments do you see against just swallowing the exception as a 'known limitation' and moving on?
My reason for using Server.Transfer in this one very specific case is that I want to mask the (real) target url of the page that is actually executing. It works pretty well, except for this exception (that the user never sees).
Make sure you are not calling Server.Transfer() within an exception handler (try..catch/finally).
Edit:
Server.Transfer always raises ThreadAbortException upon completion. If you wrap it in an exception handler you should trap for explicit exception types instead of just 'Exception'.
See the help for Server.Transfer on MSDN. Here is info about ThreadAbortException

Resources