Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

@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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 = 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading