AOP面向切面编程,是对OOP(面向对象编程)的延续,可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低。
springboot使用aop第一步当然是引入相关的jar包,采用maven引入直接添加 spring-boot-starter-aop 的依赖坐标,可通过maven依赖查询网址来查找坐标,导入依赖。
然后新建一个FisheryException异常类,继承RuntimeException,类名可以自定义,code为异常代码,message则为异常信息。
public class FisheryException extends RuntimeException {
private Integer code;
private String message;
public FisheryException(ServiceExceptionEnum exceptionEnum) {
this.code = exceptionEnum.getCode();
this.message = exceptionEnum.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
然后新建一个ServiceExceptionEnum接口,用于获取异常代码,和异常信息。
public interface ServiceExceptionEnum {
Integer getCode();
String getMessage();
}
新建 FisheryExceptionEnum 枚举类并实现 ServiceExceptionEnum 接口,枚举系统中出现的错误信息,
public enum FisheryExceptionEnum implements ServiceExceptionEnum {
/**
* 文件上传
*/
FILE_READING_ERROR(400, "FILE_READING_ERROR!"),
FILE_NOT_FOUND(400, "FILE_NOT_FOUND!"),
UPLOAD_ERROR(500, "上传图片出错");
/**
*这里可以继续添加自己用到的异常信息
*
*/
private Integer code;
private String message;
FisheryExceptionEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
@Override
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
接下来,便是重中之重的一步,新建统一的异常处理类,并添加 @ControllerAdvice 的注解,对于内部异常拦截的方法则需要添加以下的注解
// 这里的异常类及为自开始自定义的异常类,可自行修改为自己的类名
@ExceptionHandler(FisheryException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
贴出具体的完整的代码,其中ErrorTip为自定义的返回json数据的类,可自行修改,为String等,或自己新建ErrorTip的类,其中包括code,和message两个字段。
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 拦截业务异常
*
* @param e
* @return
*/
@ExceptionHandler(FisheryException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFound(FisheryException e) {
LOGGER.error("业务异常", e);
return new ErrorTip(e.getCode(), e.getMessage());
}
/**
* 拦截未知的运行时异常
*
* @param e
* @return
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFound(RuntimeException e) {
LOGGER.error("运行时异常:", e);
return new ErrorTip(FisheryExceptionEnum.SERVER_ERROR.getCode(), FisheryExceptionEnum.SERVER_ERROR.getMessage());
}
}
以上就是springboot统一异常处理的方法。在实际的controller类中对于异常可通过throw new Exception的方法返回异常。