Spring boot 全局异常捕获非常简单。
非常简单
@ControllerAdvice Controller增强 会拦截Controller中的 你配置的事件。
那些事件呢??
在工程中通常会配置一些 自己抛出的异常 或者 系统抛出的异常
//捕获所有Exception 异常
@ExceptionHandler(Exception.class)
//捕获MyException异常 MyException 就是你自己定义的
@ExceptionHandler(MyException.class)
//捕获MyException异常 BusinessException 也是自己定义的这样你就可以分别处理了
@ExceptionHandler(BusinessException.class)
关于自定义的异常可以继承 RuntimeException
public class BusinessException extends RuntimeException {
private Integer code;
private String errorMessage;
public ServiceException(Integer code, String errorMessage) {
super(errorMessage);
this.code = code;
this.errorMessage = errorMessage;
}
public ServiceException(AbstractBaseExceptionEnum exception) {
super(exception.getMessage());
this.code = exception.getCode();
this.errorMessage = exception.getMessage();
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
//下面是关机代码,
@ControllerAdvice
public class ControllerLog {
private Logger log = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(NoUserException.class)
@ResponseStatus(HttpStatus.OK) //返回状态码 设置 ok 就是 200
public String handleException(NoUserException e, Model model) {
//比如 捕获 MyException 我想存数据库
model.addAttribute("tips","没有该用户");
return "/login.html";
}
@ExceptionHandler(BusinessException.class)
@ResponseBody //如果要返回json 需要使用该注解
public Error handleException(BusinessException e) {
//比如 捕获 BusinessException 我正常返回,但是告诉客服输入错误
log.error("业务日志异常", e);
return new Error(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException(Exception e) {
log.error("服务器异常", e);
return "/error.html";
}
}