全局异常参数错误提示优化

This commit is contained in:
gaoqr
2025-03-22 10:36:45 +08:00
parent 6b95a80f56
commit d1450061d0
@@ -14,6 +14,7 @@ import com.cf.imes.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
@@ -144,7 +145,7 @@ public class GlobalExceptionHandler {
String defaultMessage = fieldError.getDefaultMessage();
// 如果是校验器来的给出校验注解的提示
if (CharSequenceUtil.isNotEmpty(defaultMessage) && fieldError.contains(ConstraintViolation.class)) {
return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", defaultMessage));
return CommonResult.error(BAD_REQUEST.getCode(), defaultMessage);
} else {
return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确,%s:%s", fieldError.getField(), fieldError.getRejectedValue()));
}
@@ -157,7 +158,12 @@ public class GlobalExceptionHandler {
public CommonResult constraintViolationExceptionHandler(ConstraintViolationException ex) {
log.warn("[constraintViolationExceptionHandler]", ex);
ConstraintViolation constraintViolation = ex.getConstraintViolations().iterator().next();
return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", constraintViolation.getMessage()));
String message = constraintViolation.getMessage();
if (StringUtils.isNotEmpty(message)) {
return CommonResult.error(BAD_REQUEST.getCode(), message);
} else {
return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", message));
}
}
/**