Skip to content

全局增强类(统一异常、全局处理)

全局统一处理 Controller 层的异常、统一响应格式,避免重复编码,提升项目规范性。

注解 作用说明
@RestControllerAdvice 全局增强 Controller,作用于所有带 @RestController 的类,可用于全局异常处理、响应格式封装
@ExceptionHandler 配合 @RestControllerAdvice 使用,指定要捕获的异常类型,处理该类型的所有异常
// 1. 统一响应结果(封装返回格式,避免重复编写)
@Data
public class R<T> {
    // 状态码:200=成功,500=异常
    private int code;
    // 提示信息
    private String msg;
    // 响应数据
    private T data;

    // 成功响应(带数据)
    public static <T> R<T> ok(T data) {
        R<T> r = new R<>();
        r.setCode(200);
        r.setMsg("success");
        r.setData(data);
        return r;
    }

    // 异常响应(带提示)
    public static <T> R<T> error(String msg) {
        R<T> r = new R<>();
        r.setCode(500);
        r.setMsg(msg);
        return r;
    }
}

// 2. 全局异常处理(@RestControllerAdvice + @ExceptionHandler)
@RestControllerAdvice // 全局增强所有 Controller
public class GlobalExceptionHandler {

    // 捕获所有 Exception 异常(最顶层异常,兜底)
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e) {
        // 输出异常信息(便于调试)
        e.printStackTrace();
        // 返回统一异常响应
        return R.error("系统异常:" + e.getMessage());
    }

    // 捕获特定异常(如空指针异常),优先级高于顶层异常
    @ExceptionHandler(NullPointerException.class)
    public R<Void> handleNullPointException(NullPointerException e) {
        return R.error("空指针异常:请检查参数是否为空");
    }

    // 捕获自定义异常(实际项目中可自定义异常类型)
    @ExceptionHandler(CustomException.class)
    public R<Void> handleCustomException(CustomException e) {
        return R.error(e.getMessage());
    }
}

// 自定义异常(示例)
public class CustomException extends RuntimeException {
    public CustomException(String message) {
        super(message);
    }
}

// 3. 测试全局异常与统一响应
@RestController
@RequestMapping("/exception")
public class ExceptionController {
    @GetMapping("/null")
    public R<Void> testNull() {
        // 模拟空指针异常
        String str = null;
        str.length();
        return R.ok(null);
    }

    @GetMapping("/custom")
    public R<Void> testCustom() {
        // 抛出自定义异常
        throw new CustomException("自定义异常:参数不合法");
    }

    @GetMapping("/success")
    public R<User> testSuccess() {
        User user = new User();
        user.setUsername("测试成功");
        return R.ok(user); // 统一成功响应
    }
}