Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception from @ExceptionHandler to get caught by another handler

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?

like image 373
agentgonzo Avatar asked Mar 29 '16 10:03

agentgonzo


People also ask

What happens if an exception is thrown during the handling of an exception?

If the exception-handling implementation catches you doing either, it will terminate your program.

When an exception object is thrown it is caught by?

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.

Who should be responsible for catching and handling exceptions?

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

What is exception Handler exception?

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.


1 Answers

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
}
like image 153
Mayday Avatar answered Oct 29 '22 15:10

Mayday