1. 导入依赖
版本跟随父类spring-boot-starter-parent
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. 处理器
下述所有类都缺少package,需根据自身包名进行指定
import com.yh.reggie.common.Information;
import com.yh.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* date 2022/12/25
*
* @author yu
* 全局异常处理器
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理sql异常 约束冲突约束
*
* @return 传输给前端异常信息
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
//打印日志
log.error(exception.getMessage());
//判断是否有Duplicate entry 重复条目错误信息
if (exception.getMessage().contains(Information.INTEGRITY_CONSTRAINT)) {
//分割
String[] split = exception.getMessage().split(" ");
//将重复条目输出
String msg = split[2] + "已存在";
return Result.error(msg);
}
return Result.error("未知错误");
}
/**
* 处理自己的异常
*/
@ExceptionHandler(CustomException.class)
public Result<String> customHandler(CustomException exception) {
log.error(exception.getMessage());
return Result.error(exception.getMessage());
}
/**
* 处理io异常
*/
@ExceptionHandler(IOException.class)
public Result<String> ioHandler(IOException exception) {
log.error(exception.getMessage());
return Result.error("文件传输错误");
}
@ExceptionHandler(IllegalStateException.class)
public Result<String> illegalStateHandler(IllegalStateException exception) {
log.error(exception.getMessage());
return Result.error("非法状态");
}
}
3. Result类
处理器中用到了统一返回类
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
/**
* date 2022/12/25
*
* @author yu
* 通用返回前端页面
*/
@Data
public class Result<T> implements Serializable {
/**编码:1成功,0和其它数字为失败*/
private Integer code;
/**错误信息*/
private String msg;
/**数据*/
private T data;
/**动态数据*/
private Map<Object,Object> map = new HashMap<>();
public static <T> Result<T> success(T object) {
Result<T> r = new Result<>();
r.data = object;
r.code = 1;
return r;
}
public static <T> Result<T> error(String msg) {
Result r = new Result();
r.msg = msg;
r.code = 0;
return r;
}
public Result<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}
4. 自定义业务异常类
在项目中可以抛出自己定义的异常做相应的处理,可自己进行扩展
/**
* date 2022/12/27
*
* @author yu
* 自定义业务异常
*/
public class CustomException extends RuntimeException {
public CustomException(String massage) {
super(massage);
}
}