您的位置:首页 > 编程语言 > Java开发

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

2018-02-24 14:57 337 查看
@ControllerAdvice的做可以可以全局拦截指定的异常,并做想要的包装处理,比如跳转到别的页面,或者返回指定的数据格式等等。此种做法的好处是成功的返回数据格式不需要与错误的一致,并且所有的错误信息格式一致。方便前台统一处理
1、新建MyControllerAdvice类
import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * <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日 下午2:25:16 XueXY 新建
 * @author XueXY
 * @since V1.00.00
 *  基于@ControllerAdvice  @EnableWebMvc  注解实现的全局异常处理器
 */
@ControllerAdvice  //@ControllerAdvice的做可以可以全局拦截指定的异常,并做想要的包装处理,比如跳转到别的页面,或者返回指定的数据格式等等。
@EnableWebMvc  //开启SpringMvc支持
public class GlobalExceptionHandler{  
  
  
    @ModelAttribute
    public void changeModel(Model model) {
        System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");
        model.addAttribute("a
4000
uthor", "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 
";
}

}


2、测试异常,模拟抛出异常[code]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;
}

}
测试效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: