1、全局异常
@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
@RestControllerAdvice
public class CustomExtHandler { private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
Object handleException(Exception e,HttpServletRequest request){
LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
} }
2、自定义异常类型
自定义异常类型MyException
/*
* 功能描述: 建立自定义异常类 -- 继承运行异常最高类
*
* */ public class MyException extends RuntimeException{ public MyException(String code, String msg){
this.code = code;
this.msg = msg;
} private String code;
private String msg; public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} }
修改CustomExtHandler
@RestControllerAdvice
public class CustomExtHandler { private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
Object handleException(Exception e,HttpServletRequest request){
LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
} /**
* 功能描述: 处理自定义异常类
* @return
*
*/
@ExceptionHandler(value = MyException.class)
Object handleMyException(MyException e, HttpServletRequest request){
//进行页面跳转
// ModelAndView modelAndView = new ModelAndView();
// modelAndView.setViewName("error.html");
// modelAndView.addObject("msg", e.getMessage());
// return modelAndView; //f返回json数据
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
}
模拟一个异常实现页面跳转
/**
* 功能描述: 模拟自定义异常
* @return
*/
@RequestMapping(value = "/api/v1/myext")
public Object myext() {
throw new MyException("500", "my ext异常");
}
最后梳理顺序:
首先,建立自定义异常类 MyException,继承于RuntimeException。如果出异常,在@RestControllerAdvice注释下的CustomExtHandler里面捕获,根据异常种类进行处理。
异常处理的官网地址: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling