Spring Boot 全局异常处理怎么捕获对账失败异常
通过定义自定义异常类并配合 @restcontrolleradvice 进行统一拦截,即可实现对账失败异常的捕获。具体做法是创建一个继承自 runtimeexception 的 reconciliationexception,并在控制器中抛出该异常,全局处理器会将其转换为标准的 json 响应。

如何区分业务对账失败与系统内部错误
在
@ExceptionHandler</code 方法中,通过判断异常类型来区分对账失败和系统错误。对账失败通常由业务逻辑触发,而系统错误如空指针或数据库连接超时则由框架自动抛出。通过分别处理这两种异常,可以返回不同的 HTTP 状态码和错误信息。</p><p><img src="https://img.php.cn/upload/article/001/242/473/179463109817019.png" alt="Spring Boot 全局异常处理怎么捕获对账失败异常"></p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer"><img
src="https://img.php.cn/upload/skill/000/000/081/179103250068943.jpg" alt="Spring Boot Actuator Analyzer" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer">Spring Boot Actuator Analyzer</a>
<p>分析Spring Boot Actuator端点的安全性、健康检查、指标暴露及生产配置——审计信息、健康状态和自定义端点。</p>
</div>
<a href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><pre class="brush:php;toolbar:false;">package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class ReconciliationController {
@GetMapping("/check")
public Map<String, Object> check() {
// 模拟对账失败场景
throw new ReconciliationException("对账数据不一致,金额差异: 100.00");
}
}
class ReconciliationException extends RuntimeException {
public ReconciliationException(String message) {
super(message);
}
}
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(ReconciliationException.class)
public ResponseEntity<Map<String, Object>> handleReconciliationError(ReconciliationException ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", "RECONCILIATION_FAILED");
body.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGenericError(Exception ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", "INTERNAL_SERVER_ERROR");
body.put("message", "系统内部错误");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
}
}
当对账失败时,前端如何获取具体的错误原因
在全局异常处理中,将异常的具体消息(getMessage())放入响应体的 <code>message 字段中。这样前端在接收到 BAD_REQUEST 状态码后,可以直接读取该字段显示给用户,例如“对账数据不一致,金额差异: 100.00”。


















