Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified about every thrown exception (even handled ones) [duplicate]

Is there a way to get notified about every single exception that is thrown during runtime (handled and unhandled)?

What I want is a logger mechanism that logs every exception that comes up while my program is running. I don't want to handle the exceptions with this logger, I just want to be able to log the event of an exception being thrown.
The thing is that I want to include all system exceptions as well therefore it is not possible to call a function whenever I throw a new exception...

I have read something about ExceptionListener but they seem to be intended for a different job.

Has anyone an idea how this would be possible?

like image 298
Raven Avatar asked Oct 30 '22 12:10

Raven


1 Answers

Exceptions are usually logged when caught (rather than thrown), so their consequences can be logged, too. That is, some exceptions have no consequences, therefore warrant no investigation, while other exceptions are extremely critical, and must be investigated whenever they occur. A good logfile should therefore convey not only that an exception occurred, but also the (business) impact of that exception, which is known only after the exception is caught. This requires that exceptions be logged when they are handled.

Therefore, there is no Java API to intercept all exceptions thrown by the running program.

However, it can sometimes help to look at all thrown exceptions. You can do so by attaching a debugger to the JVM, and set an "exception breakpoint" for all subclasses of java.lang.Throwable. Alternatively, you can write an interceptor to log all exceptions that cross some API boundary (any reasonable dependency injection container can help with that). Or you might use the Instrumentation API to add logging to classes as they are loaded.

like image 172
meriton Avatar answered Nov 08 '22 09:11

meriton