GlobalExceptionHandler.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.adx.tencent.httpapi;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.RestControllerAdvice;
  8. import org.springframework.web.server.ResponseStatusException;
  9. import java.io.IOException;
  10. import java.util.Map;
  11. /**
  12. * 全局异常处理器:对齐 Go 的 respondError(c, status, err) 返回格式 {"error": "message"}。
  13. * Go 中所有错误统一返回 {"error": "..."} + 明确的 HTTP 状态码,
  14. * Spring 默认返回 {"timestamp":..., "status":..., "error":..., "message":...} 格式不一致。
  15. */
  16. @RestControllerAdvice
  17. public class GlobalExceptionHandler {
  18. private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  19. /**
  20. * ResponseStatusException(手动抛出的带状态码的异常)。
  21. * 对应 Go: respondError(c, specificStatus, err)
  22. */
  23. @ExceptionHandler(ResponseStatusException.class)
  24. public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
  25. String reason = ex.getReason() != null ? ex.getReason() : ex.getMessage();
  26. return ResponseEntity.status(ex.getStatusCode())
  27. .body(Map.of("error", reason));
  28. }
  29. /**
  30. * IllegalArgumentException(参数校验失败)。
  31. * 对应 Go: respondError(c, http.StatusBadRequest, err)
  32. */
  33. @ExceptionHandler(IllegalArgumentException.class)
  34. public ResponseEntity<Map<String, String>> handleBadRequest(IllegalArgumentException ex) {
  35. return ResponseEntity.status(HttpStatus.BAD_REQUEST)
  36. .body(Map.of("error", ex.getMessage()));
  37. }
  38. /**
  39. * IOException / InterruptedException(外部服务调用失败)。
  40. * 对应 Go: respondError(c, http.StatusBadGateway, err)
  41. */
  42. @ExceptionHandler({IOException.class, InterruptedException.class})
  43. public ResponseEntity<Map<String, String>> handleBadGateway(Exception ex) {
  44. log.error("External service error: {}", ex.getMessage(), ex);
  45. return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
  46. .body(Map.of("error", ex.getMessage()));
  47. }
  48. /**
  49. * 兜底:所有未预期异常。
  50. * 对应 Go: respondError(c, http.StatusBadGateway, err)
  51. */
  52. @ExceptionHandler(Exception.class)
  53. public ResponseEntity<Map<String, String>> handleGeneral(Exception ex) {
  54. log.error("Unhandled exception: {}", ex.getMessage(), ex);
  55. return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
  56. .body(Map.of("error", ex.getMessage() != null ? ex.getMessage() : "internal error"));
  57. }
  58. }