spring 全局统一处理异常

记下两种方法:

一、使用注解 @controllerAdvice 和 @ExceptionHandler

@ControllerAdvice,是spring3.2提供的新注解

需要把@ControllerAdvice包含进来,否则不起作用:

<context:component-scan base-package="com.sishuok.es" use-default-filters="false">  
       <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
       <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>  
</context:component-scan>  
@ControllerAdvice  
@EnableWebMvc 
@Component 
public class GlobalExceptionHandler{  
  
    @ExceptionHandler(AjaxException.class)  
    @ResponseBody  
    public ErrorInfo<String>ajaxException(HttpServletRequest req,Exception e){  
        ErrorInfo<String> errInfo = new ErrorInfo<String>();  
        errInfo.setCode(ErrorInfo.ERROR);  
        errInfo.setMessage(e.getMessage());  
        errInfo.setUrl(req.getRequestURI().toString());  
        errInfo.setData("some data");  
        return errInfo;  
    }  
  
  
}  
在类上加注解 @ControllerAdvice 所有的异常都会被它捕获,通过 @ExceptionHandler (Exception.class)来选择不同异常的处理方法。

二、spring自定义异常拦截:

@Component  
public class MyHandlerExceptionResolver implements HandlerExceptionResolver  {  
  
    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object object, Exception exception) {  
        //是否为ajax请求  
        String requestType = request.getHeader("X-Requested-With");  
         if(exception instanceof AuthorizationException){  
            response.setStatus(413);//无权限异常  主要用于ajax请求返回  
            response.addHeader("Error-Json", "{\"code\":413,\"msg\":\"nopermission\"}");  
            response.setContentType("text/html;charset=utf-8");  
            if("XMLHttpRequest".equals(requestType)){  
                return new ModelAndView();  
            }  
            return new ModelAndView("redirect:/html/413.html");  
        }  
        return null;  
    } 
}
实现了接口 HandlerExceptionResolver 进行异常全局统一处理。



没有更多推荐了,返回首页