Issue
I want to handle all exceptions thrown by any controller with the help of my GlobalExceptionHandler class. When I add following code to my controller, it works fine. But in this case I must add following code to all my controllers. But I don't want to repeat following code in each controller.
@ExceptionHandler({ FiberValidationException.class })
public String handleValidationException(HttpServletRequest req, Exception ex)
{
return ex.getMessage();
}
When I remove them and use my GlobalExceptionHandler class, it doesn't handle exceptions.
What is the reason ? How I can fix it ?
@ControllerAdvice
@EnableWebMvc
public class GlobalExceptionHandler {
private static final Logger LOG = Logger.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler({ FiberValidationException.class })
public String handleValidationException(HttpServletRequest req, Exception ex) {
LOG.error("FiberValidationException handler executed");
return ex.getMessage();
}
@ExceptionHandler({ ChannelOverflowException.class })
public String handleOverflowException(HttpServletRequest req, Exception ex) {
LOG.error("ChannelOverflowException handler executed");
return ex.getMessage();
}
}
Solution
Extend your global exception class with ResponseEntityExceptionHandler
. e.g. public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
Answered By - kk.