Resul Rzyv RM Resul Rzyv RM -4 years ago 86
Java Question

Srping @ControllerAdvice doesn't work

I wanna handle all exceptions thrown by the any controller with the help of my GlobalExceptionHandler class.When I add following codes to my controller it works fine.But in this case I must add following codes to all my controller.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 ? Thanks to all

@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();
}
}

Answer Source

Extend your global exception class with ResponseEntityExceptionHandler. e.g. public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download