
-
定义业务异常类
- 相对于 java 的异常类,支持更多字段
- 自定义构造函数,更灵活 / 快捷的设置字段
-
编写全局异常处理器
- 捕获代码中所有的异常,内部消化,让前端得到更详细的业务报错 / 信息
- 同时屏蔽掉项目框架本身的异常(不暴露服务器内部状态)
- 集中处理,比如记录日志
- 实现 Spring AOP :在请求前后做额外的处理(类似于前端的 axios 请求拦截器)
创建一个 exception 包,在 exception 包下创建 GlobalExceptionHandler.java 全局异常处理器:
- @RestControllerAdvice: 定义一个全局的控制器异常处理类。当控制器(即使用@RestController注解的类)抛出异常时,Spring会使用这个类中定义的方法来处理异常
- @ExceptionHandler(BusinessException.class): 指定一个方法来处理特定的异常类型。在这里,它指定businessExceptionHandler方法来处理BusinessException类型的异常
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
package com.heo.matchmatebackend.exception;
import com.heo.matchmatebackend.common.BaseResponse;
import com.heo.matchmatebackend.common.ErrorCode;
import com.heo.matchmatebackend.common.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理器
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//处理异常
@ExceptionHandler(BusinessException.class) //指定能够处理的异常类型
public BaseResponse businessExceptionHandler(BusinessException e) {
log.error("businessException:" + e.getMessage(), e);
return ResultUtil.error(e.getCode(), e.getMessage(), e.getDescription());
}
//处理异常
@ExceptionHandler(RuntimeException.class)
public BaseResponse runtimeExceptionHandler(BusinessException e) {
log.error("runtimeException",e);
return ResultUtil.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "");
}
}
可以看到 RuntimeException 封装的异常类:

不够直观详细,所以我们需要自己封装,创建 BusinessException.java 自定义业务异常类:
package com.heo.matchmatebackend.exception;
import com.heo.matchmatebackend.common.ErrorCode;
/**
* 自定义异常类
*/
public class BusinessException extends RuntimeException{
private final int code;
private final String description;
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public BusinessException(String message, int code, String description) {
// 调用父级的构造函数 将自己的 message 传递给父级
super(message);
// 定义自己独有的属性
this.code = code;
this.description = description;
}
public BusinessException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
this.description = errorCode.getDescription();
}
public BusinessException(ErrorCode errorCode,String description) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
this.description = description;
}
}
1312

被折叠的 条评论
为什么被折叠?



