Home > Software design >  How to log execution time with ExceptionHandler
How to log execution time with ExceptionHandler

Time:12-13

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

@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
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 = Instant.now();
    
    try {
        // do some fancy code stuff
    } catch (Exception e) {
        logTime(Duration.between(start, Instant.now()).toMillis());
    }
} 

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.

CodePudding user response:

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 = Instant.now();
try {
  point.proceed();
} catch (Exception ex) {
  Instant end = Instant.now();
  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.

  • Related