feat(common): 全局异常处理, ResponseStatusException 统一返回 {message} (Open API/后台错误可读)
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
package me.iiv.agent.common;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 统一错误响应:业务校验抛出的 ResponseStatusException 一律返回 {"message": 原因}。
|
||||
* 后台前端与 Open API 调用方(含 agent)都按 message 字段取错误说明;
|
||||
* 未预期的异常不经过这里,避免内部细节外泄。
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<Map<String, String>> handleStatus(ResponseStatusException error) {
|
||||
String reason = error.getReason();
|
||||
return ResponseEntity.status(error.getStatusCode())
|
||||
.body(Map.of("message", reason == null || reason.isBlank() ? "请求失败" : reason));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user