Reputation: 25
I'm trying to catch the errors in a @RestController.
I present the model I am playing with:
public class CreateUpdateTodoDto {
private Long userId;
@NotNull(message = "The TODO title must not be null")
@Size(min=1, max=3, message = "Title size too large, maximum < 4")
private String title;
@NotNull
private boolean completed;
}
I present the RestController
@PostMapping("/")
public ResponseEntity<?> insert(@RequestBody @Valid CreateUpdateTodoDto dto, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new TodoConstrainValidationException(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.CREATED).body(todoService.insert(dto));
}
@PutMapping("/{id}")
public ResponseEntity<?> update(@RequestBody @Valid CreateUpdateTodoDto dto,
@PathVariable("id") int id,
HttpServletRequest request,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new TodoConstrainValidationException(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
return ResponseEntity.ok().body(todoService.update(dto, id, request));
}
In the insert method, if I send an invalid object, it detects it correctly and throws the exception as I expect, all correct for me. The problem comes with the put method, if I send an invalid object, I simply receive a response with the empty body and with status 400, now if I remove the parameters @PathVariable ("id") int id, and HttpServletRequest request, it works as it should to be. Because if you have these two parameters (int id and HttpServletRequest request), it doesn't work the same way? I leave you the photos of the responses I get with Postman.
For me it is correct, it is what is expected (within my ignorance)
Here I am already lost, I could eliminate the 2 parameters that I have commented previously and it would work, but I don't know why it acts this way.
Thank you!
Upvotes: 0
Views: 1220
Reputation: 788
The parameters order important the BindingResult
need to come after the request body that you are doing validation. Modify PuttMapping
as below.
@PutMapping("/{id}")
public ResponseEntity<?> update(@RequestBody @Valid
CreateUpdateTodoDto dto, BindingResult bindingResult,
@PathVariable("id") int id,
HttpServletRequest request )
Upvotes: 2