You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
digital-rmb-backend/src/main/java/com/yau/digitalrmb/shared/web/GlobalExceptionHandler.java

51 lines
2.2 KiB
Java

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.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<Void> handleValidation(Exception exception) {
return ApiResponse.failure(ErrorCode.VALIDATION_ERROR, exception.getMessage(), traceId());
}
@ExceptionHandler(BusinessException.class)
public ApiResponse<Void> handleBusiness(BusinessException exception) {
return ApiResponse.failure(exception.getErrorCode(), exception.getMessage(), traceId());
}
@ExceptionHandler(PlatformTokenException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ApiResponse<Void> handlePlatformToken(PlatformTokenException exception) {
return ApiResponse.failure(ErrorCode.UNAUTHORIZED, "平台登录凭据无效", traceId());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiResponse<Void> handleUnexpected(Exception exception) {
LOGGER.error("Unhandled request failure", exception);
return ApiResponse.failure(ErrorCode.INTERNAL_ERROR, "系统内部错误", traceId());
}
private String traceId() {
String traceId = MDC.get(TraceIdFilter.MDC_KEY);
return traceId == null ? UUID.randomUUID().toString() : traceId;
}
}