5

Using this works fine

@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler(value = IoTException.class)
public void IoTError() {

}

But when I try to convert to another homemade exception

@ExceptionHandler(value = IoTException.class)
public void IoTError() {
    throw new IoTConnectionException();
}

Exception handler is ignored, i.e. IoTException are sent to the view without being converted to IoTConnectionException. But placing a breakpoint showed me enter the IoTError method. Any idea why ? Thanks :)

4
  • what is ignored? on IoTException.class you are not getting inside the @ExceptionHandler? Commented Apr 9, 2018 at 8:28
  • Edited the question to be more complete. Commented Apr 9, 2018 at 8:35
  • there is no conversion. IoTException.class gets you to the @ExceptionHandler where from you are throwing an exception. If you can see that the debugger is breaking inside the IoTError() are you saying that the exception is then not thrown? Commented Apr 9, 2018 at 8:41
  • 1
    Exception is caught by spring and interpreted as an error in the ExceptionHandler, so handler is ignored. Commented Apr 9, 2018 at 9:06

1 Answer 1

10

The docs about exception handling state:

If an exception occurs during request mapping or is thrown from a request handler such as an @Controller, the DispatcherServlet delegates to a chain of HandlerExceptionResolver beans to resolve the exception and provide alternative handling, which typically is an error response.

At the point where you are throwing the IoT exception, the delegation to the chain of HandlerExceptionResolver has already been taken place and it will not be executed again. If this exception would trigger another exception handling dispatch it could cause exception cycles. Imagine you would have defined another exception handler method for IoTConnectionException and this would throw IoTException. You would end with a StackOverflowException.

In this section Docs Exception handler methods all supported return values of an exception handler method are described.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, my exception is interpreted as a error in the handling of the exception : Failed to invoke @ExceptionHandler method, instead of as another exception to handle
There was actually a @ControllerAdvice class I wasn't aware of with another @ExceptionHandler as you guessed. I moved my handler in this class and called the former handler instead of throwing the exception, and it worked !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.