基于Spring MVC中@ControllerAdvice注解实现全局异常拦截


@ControllerAdvice的做可以可以全局拦截指定的异常,并做想要的包装处理,比如跳转到别的页面,或者返回指定的数据格式等等。此种做法的好处是成功的返回数据格式不需要与错误的一致,并且所有的错误信息格式一致。方便前台统一处理


1、新建MyControllerAdvice类

复制代码
@ControllerAdvice  //@ControllerAdvice的做可以可以全局拦截指定的异常,并做想要的包装处理,比如跳转到别的页面,或者返回指定的数据格式等等。
@EnableWebMvc  //开启SpringMvc支持
public class GlobalExceptionHandler{  
  
  
    @ModelAttribute
    public void changeModel(Model model) {
        System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");
        model.addAttribute("author", "Jim");
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器");
    }




    /**
     * 设置要捕获的异常,并作出处理
     * 注意:这里可以返回试图,也可以放回JSON,这里就当做一个Controller使用
     *
     * @param request {@link NativeWebRequest}
     * @param e {@link Exception}
     * @return {@link Map}
     */
    


    @ExceptionHandler(TestException.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;  
    }  
    
   /* @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map processUnauthenticatedException(NativeWebRequest request, Exception e) {
        System.out.println("===========应用到所有@RequestMapping注解的方法,在其抛出Exception异常时执行");
        Map map = new HashMap(5);
        map.put("code", 404);
        map.put("msg", e.getMessage());
        return map;
    }*/
} 
复制代码

public class TestException extends RuntimeException {//自定义异常类

	public TestException(String message) {
		super(message);
	}

	public TestException() {
		super();
	}

}
 //返回json的错误信息封装类

public class ErrorInfo<T> {  
    
    public static final Integer OK = 0;  
    public static final Integer ERROR = -1;  
      
    private Integer code;  
    private String message;  
    private String url;  
    private T data;  
      
    public ErrorInfo() {  
          
    }  
      
    public ErrorInfo(Integer code) {  
        this.code = code;  
          
    }  
      
    public ErrorInfo(Integer code,String message) {  
        this.code = code;  
        this.message = message;   
    }  
      
    public ErrorInfo(Integer code,String message,String url) {  
        this.code = code;  
        this.message = message;   
        this.url = url;  
    }  
      
    public ErrorInfo(Integer code,String message,String url,T data) {  
        this.code = code;  
        this.message = message;   
        this.url = url;  
        this.data = data;  
    }  
  
    public Integer getCode() {  
        return code;  
    }  
  
    public void setCode(Integer code) {  
        this.code = code;  
    }  
  
    public String getMessage() {  
        return message;  
    }  
  
    public void setMessage(String message) {  
        this.message = message;  
    }  
  
    public String getUrl() {  
        return url;  
    }  
  
    public void setUrl(String url) {  
        this.url = url;  
    }  
  
    public T getData() {  
        return data;  
    }  
  
    public void setData(T data) {  
        this.data = data;  
    }  
  
    public static Integer getOk() {  
        return OK;  
    }  
  
    public static Integer getError() {  
        return ERROR;  
    }  
  
    @Override  
    public String toString() {  
        return "ErrorInfo [code=" + code + ", message=" + message + ", url=" + url + ", data=" + data + "]";  
    }  
      
      
}  



2、测试异常,模拟抛出异常

public int testLogin(User user,HttpSession session){
     int a=0;
    if(a==0){
	 throw new TestException("Login函数调用出错");  	    	
    }
}

测试效果:


参考博客:https://www.cnblogs.com/EasonJim/p/7887646.html

另一种和公司里前辈请教的方法:需错误与正确的返回类型一致,只是状态码不同

public ErrorBean testLogin(User user,HttpSession session){
		String name="";
		String password="";
		String userId="";
		int rs=-1;
		userId=user.getUserId();
	    password=user.getUserPassword();
	    
	    try {
	    	int a=0/0;
		} catch (Exception e) {
			return new ErrorBean("-1", "登录时出错");
		}
		return new ErrorBean();
	}
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <br>
 * ------------------------------------------------------------<br>
 * History<br>
 * ------------------------------------------------------------<br>
 * Legend:<br>
 *  (+) added feature<br>
 *  (-) deleted feature<br>
 *  (#) fixed bug<br>
 *  (^) upgraded implementation<br>
 *<br>
 * V1.00.00 2018年2月24日 下午3:03:51 XueXY 新建
 * @author XueXY
 * @since V1.00.00
 */
@ResponseBody
public class ErrorBean {
	private String code;
	private String errorMsg;
	/**
	 * @param code
	 * @param errorMsg
	 * @author XueXY
	 * @date 2018年2月24日 下午3:06:10
	 */
	public ErrorBean(String code, String errorMsg) {
		super();
		this.code = code;
		this.errorMsg = errorMsg;
	}
	public ErrorBean() {
		super();
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getErrorMsg() {
		return errorMsg;
	}
	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}
	
	

}

测试效果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值