Skip to content

SpringBoot全局异常处理,统一返回格式

@RestControllerAdvice + @ExceptionHandler:注解

java
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理业务自定义异常
    @ExceptionHandler(BusinessException.class)
    public ResponseResult handleBusinessException(BusinessException e) {
        return ResponseResult.fail(e.getCode(), e.getMessage());
    }

    // 处理参数校验异常(如@Valid注解触发的BindException)
    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(BindException e) {
        String errorMsg = e.getAllErrors().get(0).getDefaultMessage();
        return ResponseResult.fail(400, "参数校验失败:" + errorMsg);
    }

    // 兜底处理所有未捕获异常
    @ExceptionHandler(Exception.class)
    public ResponseResult handleGlobalException(Exception e) {
        log.error("系统异常:", e); // 记录完整堆栈信息
        return ResponseResult.fail(500, "服务器内部错误");
    }
}

定义基础异常类 BaseException,包含错误码、错误信息等通用字段,业务异常继承该类:

java
public class BaseException extends RuntimeException {
    private final int code; // 业务错误码(如1001表示参数错误)
    private final String message; // 友好错误信息

    public BaseException(int code, String message) {
        this.code = code;
        this.message = message;
    }
    // Getter方法省略
}

优势:便于后续按错误码分类处理(如权限异常、业务逻辑异常),支持前端根据错误码展示不同提示。

(二)统一响应格式:避免 “前后端协议混乱”

定义通用响应类 ResponseResult,确保所有异常响应遵循一致格式:

应用场景:无论正常响应还是异常响应,均返回 ResponseResult 对象,前端可统一解析 code 字段判断处理逻辑。

(三)参数校验异常的优雅处理

结合 Spring 的@Valid 注解,全局捕获 MethodArgumentNotValidException 或 BindException,提取字段级错误信息:

java
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    List<String> errors = e.getBindingResult()
        .getFieldErrors()
        .stream()
        .map(fieldError -> fieldError.getField() + ":" + fieldError.getDefaultMessage())
        .collect(Collectors.toList());
    return ResponseResult.fail(400, "参数校验失败", errors);
}

效果:前端可精准定位错误字段(如 “username:用户名不能为空”),提升交互体验。

https://doc.feiniaojin.com/graceful-response/home.html