I have a @ControllerAdvice
class to handle exceptions from my SpringMVC controllers. I would like to catch an exception of a known type (RuntimeException) in an @ExceptionHandler
method then throw the e.getCause()
exception and have this exception caught by the same @ControllerAdvice class.
Sample code:
@ControllerAdvice
public class ExceptionHandlingAdvice
{
@ExceptionHandler( RuntimeException.class )
private void handleRuntimeException( final RuntimeException e, final HttpServletResponse response ) throws Throwable
{
throw e.getCause(); // Can be of many types
}
// I want any Exception1 exception thrown by the above handler to be caught in this handler
@ExceptionHandler( Exception1.class )
private void handleAnException( final Exception1 e, final HttpServletResponse response ) throws Throwable
{
// handle exception
}
}
Is this possible?
If the exception-handling implementation catches you doing either, it will terminate your program.
When exceptions are thrown, they may be caught by the application code. The exception class extends Throwable . The constructor contains two parameters: message and cause.
The one responsible for catching and handling exceptions is the computer program. In Java, “an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions” (Oracle, n., par. 1).
An exception handler is code that stipulates what a program will do when an anomalous event disrupts the normal flow of that program's instructions. An exception, in a computer context, is an unplanned event that occurs while a program is executing and disrupts the flow of its instructions.
You can check if that RuntimeException is instance of Exception1.class and call the method directly:
private void handleRuntimeException( final RuntimeException e, final HttpServletResponse response ) throws Throwable
{
if (e instanceof Exception1) handleAnException(e,response);
else throw e.getCause(); // Can be of many types
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With