如果缺少特定欄位或該欄位為空白,我正在嘗試向我的 DTO 添加驗證然后應該拋出一個錯誤,即特定欄位丟失或不存在我正在使用物件映射器來映射欄位,例如
StudentDto studentDto = mapper.convertValue(jsonObject, StudentDto.class);
DTO 類
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class StudentDto {
@NotNull(message = "FirstName is null")
@NotBlank(message = "FirstName is missing")
String firstName;
@NotNull(message = "LastName is null")
@NotBlank(message = "LastName is missing")
String lastName;
}
我將從 jsonObject 接收所有值,然后將這些值映射到 DTO。當特定欄位丟失或為空時,應引發錯誤。但目前我沒有收到錯誤程式成功執行我該怎么做才能實作這一點
uj5u.com熱心網友回復:
使用 Jackson 2.6,您可以使用 required,盡管您必須為每個欄位定義一個使用@JsonCreator和使用注釋的建構式,@JsonProperty(required = true)以強制 Jackson 在您的 JSON 的缺失和空欄位上引發例外。
來自檔案:
請注意,從 2.6 開始,此屬性僅用于 Creator 屬性,以確保 JSON 中存在屬性值:對于其他屬性(使用 setter 或可變欄位注入的屬性),不執行驗證。將來可能會增加對這些情況的支持。此屬性的狀態通過自省公開,其值通常由 Schema 生成器使用,例如用于 JSON Schema 的生成器。
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class StudentDto {
String firstName;
String lastName;
@JsonCreator
public StudentDto(@JsonProperty(value = "firstName", required = true) String firstName,//
@JsonProperty(value = "lastName", required = true) String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
uj5u.com熱心網友回復:
在請求中,您必須在手動映射之前驗證輸入,
在控制器中必須在您的請求正文之前添加@valid
@PostMapping(value = "/addStudent ", produces = MediaType.APPLICATION_JSON_VALUE)
public Response addStudent(@Valid @RequestBody StudentDto refundReq ) {
// your code here ...
}
````
// 還有我的建議是創建一個控制器顧問來處理錯誤
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
// List<String> details = new ArrayList<>();
for (ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
logger.error(error.getDefaultMessage());
}
// your code to handel response ....
return new ResponseEntity<>(resp, HttpStatus.OK);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495994.html
上一篇:如何更改Yup中的默認錯誤訊息
