1, 新建立一个捕获异常的实体类
如: LeeExceptionHandler
- package com.leecx.exception;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
- @ControllerAdvice
- public class LeeExceptionHandler {
- public static final String DEFAULT_ERROR_VIEW = "error";
- @ExceptionHandler(value = Exception.class)
- public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception {
- e.printStackTrace();
- if (isAjax(reqest)) {
- return response;
- } else {
- ModelAndView mav = new ModelAndView();
- mav.addObject("exception", e);
- mav.addObject("url", reqest.getRequestURL());
- mav.setViewName(DEFAULT_ERROR_VIEW);
- return mav;
- }
- }
- public static boolean isAjax(HttpServletRequest httpRequest){
- return (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals( httpRequest.getHeader("X-Requested-With").toString()) ) ;
- }
- }
在类上面加入注解:@ControllerAdvice
在处理方法上面加入注解 @ExceptionHandler(value = Exception.class)
然后设置相应的业务处理. 跳转到 特需的处理错误的友好业务界面.
来源: http://www.bubuko.com/infodetail-2559133.html