Springboot项目全局异常处理
1.ErrorCode.java
package com.hng.config.exception.error;/*** @Author: 郝南过* @Description: TODO* @Date: 2023/11/14 10:56* @Version: 1.0*/
public interface ErrorCode {String getCode();String getMessage();
}
2.ErrorEnum.java
package com.hng.config.exception.error;public enum ErrorEnum implements ErrorCode {/*** 成功*/SUCCESS("SUCCESS", "成功"),//*********************系统异常*********************///*** 请求失败(外域请求等)*/REQUEST_FAIL("REQUEST_FAIL", "请求失败"),/*** 系统异常*/SYSTEM_ERROR("SYSTEM_ERROR", "系统异常"),/*** 操作超时*/OP_TIMEOUT("OP_TIMEOUT", "操作超时,请重试"),/*** 操作冲突(乐观锁、并发)*/OP_CONFLICT("OP_CONFLICT", "操作冲突"),/*** 数据库执行错误*/DB_ERROR("DB_ERROR", "数据库执行错误"),//*********************业务类异常*********************///*** 参数错误*/PARAMETER_ERROR("PARAMETER_ERROR", "参数错误"),/*** 没有权限*/NO_PRIVILEGE("NO_PRIVILEGE", "没有权限"),/*** 数据异常(数据校验不通过等)*/DATA_ERROR("DATA_ERROR", "数据异常"),/*** 数据不存在(数据校验等)*/DATA_NOT_FOUND("DATA_NOT_FOUND", "数据不存在"),/*** 数据已存在(数据校验等)*/DATA_EXIST("DATA_EXIST", "数据已存在");/*** 结果码*/private String code;/*** 结果信息*/private String message;ErrorEnum(String code, String message) {this.code = code;this.message = message;}@Overridepublic String getCode() {return this.code;}@Overridepublic String getMessage() {return this.message;}
}
3.BizException.java
package com.hng.config.exception;import com.hng.config.exception.error.ErrorEnum;
import lombok.Data;/*** @Author: 郝南过* @Description: TODO* @Date: 2023/11/14 15:43* @Version: 1.0*/
@Data
public class BizException extends RuntimeException {private String errorCode;public BizException(String msg) {super(msg);}public BizException(String errorCode, String msg) {super(msg);this.errorCode = errorCode;}public BizException(String errorCode,String msg,Throwable throwable) {super(msg, throwable);this.errorCode = errorCode;}public BizException(ErrorEnum errorEnum) {super(errorEnum.getMessage());this.errorCode = errorEnum.getCode();}public String getErrorCode() {return errorCode;}
}
4.GlobalExceptionHandler.java
package com.hng.config.exception.advice;import com.hng.config.exception.BizException;
import com.hng.config.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;/*** @Author: 郝南过* @Description: 统一处理异常类* @Date: 2023/11/14 15:49* @Version: 1.0*/
@Slf4j
@RestControllerAdvice //声明GlobalExceptionHandler作为全局异常处理类
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class) //@ExceptionHandler注解指定某个方法处理对应的错误类型,根据异常类型选择最精确的处理方法进行处理public Result exceptionHandler(Exception e){// 记录异常信息到日志文件log.error("An exception occurred: ", e);// 判断是否为自定义的异常类型if(e instanceof BizException){BizException bizException = (BizException)e;return Result.Result(bizException.getErrorCode(),e.getMessage(),null);}return Result.Result("500",e.getMessage(),null);}
}