Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC : the best way to handle exception for Ajax Request and normal request?

I want to define a common exception manger in my project, so I use @ControllerAdvice to do, the snippet of code is 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. That's great for normal exception of request. But if this is a Ajax request, the result is so ugly. so I add the code to judge it. The added code is 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 it is the best way, anybody have a good opinion?

like image 256
Rocky Hu Avatar asked Nov 10 '22 16:11

Rocky Hu


1 Answers

I have all my controllers in different packages based on whether they serve AJAX requests or not. Then I can set #basePackages element on the ControllerAdvice annotations to handle the exception accordingly

Update: See RequestMapping#params and RequestMapping#headers to separate controllers based on headers and/or params

like image 185
kranthi117 Avatar answered Nov 14 '22 23:11

kranthi117