Matthias Beaupère
Matthias Beaupère

Reputation: 1847

Spring boot exception handler : throw an exception

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

Upvotes: 5

Views: 6589

Answers (1)

Javatar81
Javatar81

Reputation: 659

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.

Upvotes: 10

Related Questions