I want to define a common exception box in my project, so I use @ControllerAdvice to do the code snippet below:
@ExceptionHandler(Exception.class) public ModelAndView handleAllException(HttpServletRequest request, Exception ex) throws Exception { LOGGER.error(ex.getMessage()); ModelAndView mav = new ModelAndView(); mav.addObject("exception", ex); mav.addObject("url", request.getRequestURL()); mav.setViewName(ViewConstants.INTERNAL_ERROR_VIEW); return mav; }
it will return a common error page. This is great for a normal query exception. But if it's an Ajax request, the result is so ugly. so I am adding code to judge this. The added code is shown below:
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { // return HTTP Status code and response message } else { // return error page name }
I donβt think this is the best way, does anyone have a good opinion?
source share