SpringBoot全局异常处理,企业实际项目全局异常封装处理与写法
- 1、全局异常处理是什么?
- 2、全局异常处理工具类
- 2.1、Result.java
- 2.2、GlobalExceptionHandler.java
- 2.3、BizException.java
- 2.4、BizAssertUtils.java
- 2.5、业务代码抛异常的用法
1、全局异常处理是什么?
在Spring Boot中,全局异常处理通过@RestControllerAdvice或@ControllerAdvice注解实现,可统一捕获并处理应用中的异常,返回结构化的错误信息。
2、全局异常处理工具类
2.1、Result.java
统一返回给前端的工具类
import lombok.Data;
import java.io.Serializable;
@Data
public class Result<T> implements Serializable {/*** 请求返回码*/private int code;/*** 请求返回状态*/private boolean status;/*** 请求返回内容*/private String message;/*** 请求返回对象*/private T data;public Result() {}/*** 成功的返回结构** @param data 类对象*/public static <T> Result<T> success(T data) {Result<T> result = new Result<>();result.setCode(200);result.setMessage("请求成功");result.setStatus(true);result.setData(data);return result;}/*** 成功的返回结构*/public static <T> Result<T> success() {Result<T> result = new Result<>();result.setCode(200);result.setMessage("请求成功");result.setStatus(true);return result;}/*** 成功的返回结构** @param data 类对象*/public static <T> Result<T> success(String message, T data) {Result<T> result = new Result<>();result.setCode(200);result.setMessage(message);result.setStatus(true);result.setData(data);return result;}public static <T> Result<T> fail(String message) {Result<T> result = new Result<>();result.setCode(500);result.setMessage(message);result.setStatus(false);result.setData(null);return result;}public static <T> Result<T> fail() {Result<T> result = new Result<>();result.setCode(500);result.setMessage("请求失败");result.setStatus(false);result.setData(null);return result;}
}
2.2、GlobalExceptionHandler.java
全局异常处理类
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/*** 全局异常类*/
@Slf4j
@RestControllerAdvice
@ConditionalOnClass(value = HttpServletRequest.class)
public class GlobalExceptionHandler {/*** 兜底异常处理** @param exception* @param request* @return*/@ExceptionHandler(Exception.class)@ResponseStatus(HttpStatus.OK)public Result<String> handleException(Exception exception, HttpServletRequest request) {log.error("\nService Request:{},\nerror message:{}\nerror location:{}", request.getRequestURI(), exception.getMessage(),simpleExceptionTargetInfo(exception));return Result.fail(exception.getMessage());}/*** 业务异常** @param bizException 业务异常* @param request HttpServletRequest*/@ExceptionHandler(BizException.class)@ResponseStatus(HttpStatus.OK)public Result<String> handleException(BizException bizException, HttpServletRequest request) {log.error("\nService Request:{},\nerror message:{}\nerror location:{}", request.getRequestURI(), bizException.getErrorMessage(),simpleExceptionTargetInfo(bizException));return Result.fail(bizException.getErrorMessage());}private String simpleExceptionTargetInfo(Throwable ex) {StringBuffer sb = new StringBuffer();if (ex == null) {return "";}StackTraceElement[] stackTraceElements = ex.getStackTrace();if (stackTraceElements == null) {return "";}for (int i = 0; i < stackTraceElements.length; i++) {StackTraceElement ste = stackTraceElements[i];if (!BizException.class.getName().equals(ste.getClassName())&& !BizAssertUtils.class.getName().equals(ste.getClassName())) {sb.append(ste.getClassName()).append(".").append(ste.getMethodName()).append("(").append(ste.getLineNumber()).append(")");break;}}return sb.toString();}
}
2.3、BizException.java
自定义异常类
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/*** 自定义异常类*/
@Slf4j
@Data
public class BizException extends RuntimeException {/*** 错误消息*/private String errorMessage;/*** 错误code*/private int errorCode;/*** 构造 Biz exception 的实例.*/public BizException() {this.errorMessage = super.getMessage();this.errorCode = 500;}/*** 构造 Biz exception 的实例.** @param message 错误信息*/public BizException(String message) {super(message);this.errorMessage = super.getMessage();this.errorCode = 500;}/*** 构造 Biz exception 的实例.** @param message 错误信息*/public BizException(String message, int errorCode) {super(message);this.errorMessage = super.getMessage();this.errorCode = errorCode;}/*** 构造 Biz exception 的实例.** @param throwable the throwable*/public BizException(Throwable throwable) {super(throwable);this.errorMessage = throwable.getMessage();this.errorCode = 500;}/*** 构造 Biz exception 的实例.** @param message the frd message* @param throwable the throwable*/public BizException(String message, Throwable throwable) {super(message, throwable);this.errorMessage = message;this.errorCode = 500;}
}
2.4、BizAssertUtils.java
业务异常断言工具类,该类不用也行,就是个抛异常的工具类,更简便
import org.apache.commons.lang3.StringUtils;import java.text.MessageFormat;
import java.util.Collection;/*** 业务异常断言工具类*/
public class BizAssertUtils {public BizAssertUtils() {}public static void isNull(Object object, String message, Object... args) {if (object == null) {throw new BizException(MessageFormat.format(message, args));}}public static void isEmpty(Collection<?> collection, String message, Object... args) {if (collection != null && collection.size() != 0) {throw new BizException(message);}}public static void isFalse(boolean flag, String message, Object... args) {if (flag) {throw new BizException(message);}}public static void fail(String message, Object... args) {throw new BizException(message);}public static void isEmpty(String str, String message, Object... args) {if (StringUtils.isEmpty(str)) {throw new BizException(message);}}
}
2.5、业务代码抛异常的用法
@Overridepublic void exc1() {//第一种写法BizAssertUtils.isNull(null,"对象{0},{1}不能为空","xiaoming","xiaozhang");//第二种写法//throw new BizException("你好");}