1 maven依赖
<!-- Hibernate Validator 用于数据验证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2 controller 请求实体
@Slf4j
@Validated
public class TestController {
@PostMapping(value = "/v1/chat/completions")
public Flux<AgentChatVo> chat(@Valid @RequestBody AgentChatRequest request) {
return agentServiceService.chat(request);
}
}
@Data
public class AgentChatRequest {
@Schema(description = "")
private String model;
@Schema(description = "是否开启stream模式")
private Boolean stream = false;
@NotEmpty(message = "The messages cannot be null.")
@Valid
private List<Message> messages;
@ApiModelProperty(hidden = true, value = "aigc 是否使用 ")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
private Boolean context = false;
@Schema(description = "最大长度")
@JsonProperty(value = "max_tokens")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
private String maxTokens;
}
@Data
public class Message {
@Schema(description = "角色")
@ApiModelProperty(hidden = true)
private String role;
@Schema(description = "问题内容")
@NotBlank(message = "The content cannot be blank.")
private String content;
public void initRole() {
if (StringUtils.isBlank(this.role)) {
this.role = AiChatRoleEnum.USER.getCode();
}
}
}
3 GlobalExceptionHandler
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler implements ResponseBodyAdvice, RequestBodyAdvice {
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity<Result<Void>> errHandler(MethodArgumentNotValidException exception) {
log.error("MethodArgumentNotValidException e:", exception);
String errorMsg = paramException(exception.getBindingResult());
return ResponseEntity.status(HttpStatus.OK).body(Result.fail(ResultCodeEnum.PARAM_ILLEGAL.code(), errorMsg));
}
private String paramException(BindingResult bindingResult) {
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
StringBuilder errorMsg = new StringBuilder();
for (FieldError fieldError : fieldErrors) {
String defaultMessage = fieldError.getDefaultMessage();
if (StringUtils.isNotBlank(defaultMessage)) {
errorMsg.append(
String.format("%s的 %s 字段异常: %s;", "入参实体", fieldError.getField(), defaultMessage));
} else {
errorMsg.append(
String.format("%s的%s字段不能被赋值为%s;", "入参实体", fieldError.getField(),
fieldError.getRejectedValue()));
}
}
return errorMsg.toString();
}
}
4 测试