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 进行异常全局统一处理。



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值