package com.yau.digitalrmb.shared.web; import com.yau.digitalrmb.shared.api.ApiResponse; import com.yau.digitalrmb.shared.api.ErrorCode; import com.yau.digitalrmb.shared.exception.BusinessException; import com.yau.digitalrmb.platformintegration.application.PlatformTokenException; import javax.validation.ConstraintViolationException; import org.slf4j.MDC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.UUID; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler({ConstraintViolationException.class, MethodArgumentNotValidException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ApiResponse handleValidation(Exception exception) { return ApiResponse.failure(ErrorCode.VALIDATION_ERROR, exception.getMessage(), traceId()); } @ExceptionHandler(BusinessException.class) public ResponseEntity> handleBusiness(BusinessException exception) { ApiResponse response = ApiResponse.failure(exception.getErrorCode(), exception.getMessage(), traceId()); return ResponseEntity.status(httpStatus(exception.getErrorCode())).body(response); } @ExceptionHandler(PlatformTokenException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ApiResponse handlePlatformToken(PlatformTokenException exception) { return ApiResponse.failure(ErrorCode.UNAUTHORIZED, "平台登录凭据无效", traceId()); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ApiResponse handleUnexpected(Exception exception) { LOGGER.error("Unhandled request failure", exception); return ApiResponse.failure(ErrorCode.INTERNAL_ERROR, "系统内部错误", traceId()); } private static HttpStatus httpStatus(ErrorCode errorCode) { switch (errorCode) { case VALIDATION_ERROR: return HttpStatus.BAD_REQUEST; case UNAUTHORIZED: return HttpStatus.UNAUTHORIZED; case FORBIDDEN: return HttpStatus.FORBIDDEN; case RESOURCE_NOT_FOUND: return HttpStatus.NOT_FOUND; default: return HttpStatus.INTERNAL_SERVER_ERROR; } } private String traceId() { String traceId = MDC.get(TraceIdFilter.MDC_KEY); return traceId == null ? UUID.randomUUID().toString() : traceId; } }