Java SpringBoot全局异常处理注解 @ControllerAdvice + @ExceptionHandler
1、统一返回结构体:
import lombok.Data; @Data public class Result<T> { private Integer code; // 状态码 200成功 500异常 private String msg; private T data; public static <T> Result<T> success(T data) { Result<T> res = new Result<>(); res.setCode(200); res.setMsg("操作成功"); res.setData(data); return res; } public static <T> Result<T> fail(Integer code, String msg) { Result<T> res = new Result<>(); res.setCode(code); res.setMsg(msg); res.setData(null); return res; } }
2、自定义业务异常
public class BusinessException extends RuntimeException { private Integer code; public BusinessException(Integer code, String message) { super(message); this.code = code; } public Integer getCode() { return code; } }
3、全局异常处理核心类
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.validation.BindException; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice // 拦截所有@RestController控制器异常 public class GlobalExceptionHandler { // 1. 自定义业务异常 @ExceptionHandler(BusinessException.class) public Result<?> businessExceptionHandler(BusinessException e, HttpServletRequest request) { return Result.fail(e.getCode(), e.getMessage()); } // 2. 参数校验异常(@Valid / @NotBlank 等校验抛出) @ExceptionHandler(BindException.class) public Result<?> bindExceptionHandler(BindException e) { String msg = e.getBindingResult().getFieldError().getDefaultMessage(); return Result.fail(400, "参数错误:" + msg); } // 3. 空指针异常 @ExceptionHandler(NullPointerException.class) public Result<?> nullPointExceptionHandler(NullPointerException e) { e.printStackTrace(); return Result.fail(500, "系统空指针异常"); } // 4. 算术异常、数组越界等通用运行时异常 @ExceptionHandler(RuntimeException.class) public Result<?> runtimeExceptionHandler(RuntimeException e) { e.printStackTrace(); return Result.fail(500, "运行异常:" + e.getMessage()); } // 5. 兜底:所有Exception最大捕获 @ExceptionHandler(Exception.class) public Result<?> exceptionHandler(Exception e) { e.printStackTrace(); return Result.fail(500, "服务器内部异常"); } }
4、测试类
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/test1") public Result<?> test1() { // 主动抛业务异常 throw new BusinessException(4001, "用户名不存在"); } @GetMapping("/test2") public Result<?> test2() { String s = null; s.length(); // 空指针 return Result.success("ok"); } }
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号