java Spring boot - Use @controlleradvice to log outOfMemoryError

288 views Asked by At

I want to log some extra details like available memory when my spring boot application gets

java.lang.OutOfMemoryError: Java heap space

I tried using the following controlleradvice class and ran the projcet after limiting available memory. But this method is never called, the application gets OutOfMemoryError and crashes.

@ControllerAdvice
public class ExceptionHandler {

@ExceptionHandler(OutOfMemoryError.class)
public void outOfMemoryErrorHandler(final OutOfMemoryError exception) {
    // log exception details with available memory 
    throw exception;
 }
}

I am not sure why this method is never called. My assumption is, it's because OutOfMemoryError is never the top level at the exception stack trace. It is always some other kind of exception depending on where the error is coming from, but it's always caused by OutOfMemoryError. So is there a way to always filter this error in Spring Boot so that no matter what the top level exception message says, if it is caused by OutOfMemoryError my custom error handler will be called? Thanks

1

There are 1 answers

0
rocco On BEST ANSWER

By default, the @ExceptionHandler annotation can only handle regular exception types and cannot handle Error types such as OutOfMemoryError. This is because Error types generally indicate serious issues that cannot be recovered by catching and handling them. You can use monitoring tools like VisualVM or JConsole to monitor memory usage and performance metrics of your application.