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 進行異常全局統一處理。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章