我是 spring-boot 的新手,我正在嘗試創建如下所示的驗證自定義。
@ControllerAdvice
@RestController
public class SpecificResponse extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
logger.info("1");
List<String> errors = new ArrayList<String>();
// String coba = requestContext.getInfo();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(error.getField() ": " error.getDefaultMessage());
}
for (ObjectError error : ex.getBindingResult().getGlobalErrors()) {
errors.add(error.getObjectName() ": " error.getDefaultMessage());
}
ApiError apiError = new ApiError();
apiError.setResponseCode("99");
apiError.setResponseDesc(ex.getBindingResult().getFieldValue("field") " Failed");
apiError.setResponseError(errors.toString());
return handleExceptionInternal(
ex, apiError, headers,HttpStatus.BAD_REQUEST, request);
}
}
下面是我的 DTO 課
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.NotFound;
import lombok.Data;
@Data
public class LiteTimeCreateDTO {
@NotNull
@NotEmpty(message = "Customer Code is required")
@NotFound
@NotBlank
private String customerCode;
@NotNull
@NotEmpty(message = "Customer Code2 is required")
@NotFound
@NotBlank
private String customerCode2;
@Email
private String customerCode3;
}
下面是我郵遞員寄來的物品
{
// "customerCode": "as",
"customerCode3": "[email protected]",
"customerCode2" : "ds"
}
下面是我在控制器中的端點
@GetMapping("")
public ResponseEntity<ApiSuccess> getData( @Valid @RequestBody(required = true) LiteTimeCreateDTO liteTimeCreateDTO, @RequestHeader(value = "User-Access") String header, BindingResult result){
ApiSuccess dataError = new ApiSuccess();
dataError.setResponseCode("00");
dataError.setResponseDesc("Get Lite Time Success");
// dataError.setResponseData(datas);
return new ResponseEntity<ApiSuccess>(dataError, HttpStatus.CREATED);
}
一切都很好,只是我很好奇如何驗證發送的 dto 不完整?當我只發送 2 個資料時,我的郵遞員沒有結果回應。如何修復并獲得錯誤回應,因為我的郵遞員沒有回應。
uj5u.com熱心網友回復:
不要在 JSON 中使用注釋。請改用以下請求正文:
{
"customerCode3": "[email protected]",
"customerCode2": "ds"
}
uj5u.com熱心網友回復:
JSON 只是資料,如果您包含注釋,那么它也將是資料。
您可以有一個名為“_comment”(或其他東西)的指定資料元素,使用 JSON 資料的應用程式應該忽略它。
您最好在生成/接收 JSON 的程序中添加注釋,因為他們應該提前知道 JSON 資料是什么,或者至少知道它的結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/335974.html
