Below is one way to handling errors in an spring MVC architecture
The class that is given provided below is an ExceptionHandler class which takes care of handing the errors that occurs in the controller and redirect to the error page
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class GlobalExceptionHandler {
private @Value("${debugmode.enabled}") Boolean isDebugModeEnabled;
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpSession session, Exception e) throws Exception {
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) throw e;
// Otherwise setup and send the user to a default error-view.
ModelAndView mav = new ModelAndView();
if(isDebugModeEnabled) {
mav.addObject("exceptionMessage", e);
} else {
mav.addObject("exceptionMessage", null);
}
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
No comments:
Post a Comment