How to log execution time with ExceptionHandler

I am trying to refactor my application and now i also want to use an ExceptionHandler.
Therefore I already implemented some Methods like

public final ResponseEntity<SomeClass> handleException(Exception e) {
// do something

Now I want to log the execution time of the calling method also when the ExeptionHandler method is called.
In my old code I did it like this:

public void doSomething() {
    Instant start =;
    try {
        // do some fancy code stuff
    } catch (Exception e) {

Has anybody an idea of how to get the information of the startTime passed in the ExceptionHandler method? Or is there maybe a much better way to get the information?

I already had a look in the Exception object structure if I could maybe find some of the needed information.

>Solution :

You can use Spring AOP to measure execution time and catch exceptions.
Here is an example. It only measures time. But you can add a try-catch there similar to what you had in your old code.

If you still want to use an ExceptionHandler, then you can create class TimeMeasuredException extends RuntimeException with executionTime field. And then do

Instant start =;
try {
} catch (Exception ex) {
  Instant end =;
  Duration executionTime = Duration.between(start, end);
  throw new TimeMeasuredException(executionTime, ex);

Your ExceptionHandler should either catch TimeMeasuredException or you can catch Exception and then check it with instanceof.

Leave a Reply