转自: 飞奔的波大爷
链接: https://blog.csdn.net/qq_22860341/article/details/81222379
拦截捕捉自定义异常 MyException.class
我的异常类:
public class MyException extends RuntimeException{
private String code; //异常状态码
private String message; //异常信息
private String method; //发生的方法,位置等
private String descinfo; //描述
public MyException(String code, String message, String method, String descinfo) {
this.code=code;
this.message=message;
this.method=method;
this.descinfo=descinfo;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDescinfo() {
return descinfo;
}
public void setDescinfo(String descinfo) {
this.descinfo = descinfo;
}
}
/**
* @Auther: cookie
* @Date: 2018/7/26 15:09
* @Description: 全局捕获异常和自定义全局捕获异常
*/
@ControllerAdvice //不指定包默认加了@Controller和@RestController都能控制
//@ControllerAdvice(basePackages ="com.example.demo.controller")
public class MyControllerAdvice {
/**
* 拦截捕捉自定义异常 MyException.class
* @param myex
* @return
*/
@ResponseBody
@ExceptionHandler(value = MyException.class)
public Map<String,Object> myExceptionHandler(MyException myex){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",myex.getCode());
map.put("message",myex.getMessage());
map.put("method",myex.getMethod());
map.put("descinfo",myex.getDescinfo());
//发生异常进行日志记录,写入数据库或者其他处理,此处省略
return map;
}
}
测试:
@RequestMapping(value = "/")
public String index() throws Exception{
String name = redisUtil.set("key100", "666");
if(StringUtils.isEmpty(name)){
throw new MyException("1001","empty","/API/getUserName","在获取用户名字的时候为空");
}
return name;
}
结果: