spring boot全局异常处理通过@controlleradvice+@exceptionhandler捕获baseexception,提取errorcode和message封装为统一result响应体,业务层直接throw baseexception即可自动返回标准json格式。

<p>在 Spring Boot 中,全局异常处理的核心是通过 <code>@ControllerAdvice</code> + <code>@ExceptionHandler</code> 捕获异常,并将自定义异常中的 <code>errorCode</code> 和 <code>message</code> 提取出来,统一封装进标准的 <code>Result</code> 响应体(如 <code>{"code": 4001, "msg": "参数不合法", "data": null}</code>)。</p>
<h3>定义统一响应体 Result</h3>
<p>先确保你有一个通用的响应结构,例如:</p>
<font color="gray">
<pre class="brush:php;toolbar:false;">
public class Result<T> {
private int code;
private String msg;
private T data;
public static <T> Result<T> success(T data) { ... }
public static <T> Result<T> fail(int code, String msg) { ... }
// getter/setter 省略
}
定义自定义异常 BaseException
让所有业务异常继承它,并携带 errorCode 和 message:
public class BaseException extends RuntimeException {
private final int errorCode;
private final String message;
public BaseException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
this.message = message;
}
// 可选:提供带 cause 的构造
public BaseException(int errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.message = message;
}
public int getErrorCode() { return errorCode; }
public String getMessage() { return message; }
}
全局异常处理器捕获并封装
用 @ControllerAdvice 编写处理器,匹配 BaseException,从中提取字段填入 Result:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BaseException.class)
@ResponseBody
public Result<Object> handleBaseException(BaseException e) {
return Result.fail(e.getErrorCode(), e.getMessage());
}
// 可选:兜底处理其他未预期异常(如 NullPointerException)
@ExceptionHandler(Exception.class)
@ResponseBody
public Result<Object> handleOtherException(Exception e) {
return Result.fail(500, "系统繁忙,请稍后再试");
}
}
业务中抛出自定义异常
控制器里直接 throw,不用手动构造 Result:
@GetMapping("/user/{id}")
public Result<User> getUser(@PathVariable Long id) {
if (id == null || id <= 0) {
throw new BaseException(4001, "用户 ID 不合法");
}
return Result.success(userService.findById(id));
}
这样调用时就会自动返回:{"code":4001,"msg":"用户 ID 不合法","data":null}。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











