使用 @restcontrolleradvice 配合 @exceptionhandler 可以捕获业务异常。具体做法是定义一个全局异常处理类,在类上标注 @restcontrolleradvice,然后编写方法并使用 @exceptionhandler 指定要捕获的自定义业务异常类型,该方法返回封装好的统一响应对象即可。

如何定义并抛出业务异常
首先需要创建一个继承自 RuntimeException 的自定义异常类,例如 BizException,用于携带错误码和消息。在业务逻辑中,当检测到非法状态时,直接 throw new BizException(...) 即可触发全局捕获。

public class BizException extends RuntimeException {
private final String code;
private final String message;
public BizException(String code, String message) {
super(message);
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public String getMessage() { return message; }
}
在 Controller 中模拟抛出异常:
@RestController
public class UserController {
@GetMapping("/user/{id}")
public Map<string object> getUser(@PathVariable Long id) {
if (id == null || id <h2>全局处理器如何返回统一JSON结构</h2>
<p>全局异常处理类中的方法接收自定义异常参数,构建包含状态码、消息和数据的标准 JSON 结构返回。Spring Boot 会自动将该对象序列化为 HTTP 响应体。</p>
<p><img src="https://img.php.cn/upload/article/001/242/473/179444419157708.png?x-oss-process=image/resize,p_40" alt="Spring Boot 全局异常处理怎么捕获业务异常"></p>
<pre class="brush:php;toolbar:false;">@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BizException.class)
public ResponseEntity<result> handleBizException(BizException ex) {
Result result = new Result(ex.getCode(), ex.getMessage(), null);
return ResponseEntity.badRequest().body(result);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<result> handleException(Exception ex) {
Result result = new Result("500", "系统内部错误", null);
return ResponseEntity.status(500).body(result);
}
}
// 统一返回结构
record Result(String code, String message, Object data) {}</result></result>
如何处理未捕获的运行时异常
除了特定的业务异常,通常还需要一个兜底处理器来捕获所有未被 @ExceptionHandler 明确处理的 Exception 或 RuntimeException。这能防止程序因未知错误而返回默认的 Tomcat 错误页面或堆栈跟踪信息,确保对外始终返回安全的 JSON 格式。











