BindException validation built-in support
See original GitHub issueI would discuss with you if org.springframework.validation.BindException
could be a great candidate to be a built-in managed exception.
Indeed when you’re validating query params rather than post body like following
@RequestMapping(path = "/handler-invalid-query-strings", method = GET)
public ResponseEntity<String> validRequestQueryStrings(@Valid final PageRequest pageRequest) {
return ResponseEntity.ok("done");
}
With PageRequest
looks like
@Data
public final class PageRequest {
@Min(value = 0)
private int page = 0;
@Min(value = 1)
private int size = 50;
}
If you try
@Test
public void invalidRequestQueryParams() throws Exception {
mvc().perform(request(GET, "http://localhost/api/handler-invalid-query-strings?page=-1"))
.andExpect(status().isBadRequest());
}
I will fail because 500
status code will be returned after Spring will throw org.springframework.validation.BindException
A bit off-topic, but can explain why:
Spring MethodValidationPostProcessor
works great with zalando:problem-spring-web
, indeed if you replace previous GetMapping
with following:
@RequestMapping(path = "/handler-invalid-query-strings", method = GET)
public ResponseEntity<String> validRequestQueryStrings(@Min(value = 0) @RequestParam(value = "page", defaultValue = "0") int page,
@Min(value = 1) @RequestParam(value="limit", defaultValue = "50") int limit) {
return ResponseEntity.ok("done");
}
I will work but since method parameter name is removed after compilation the result looks like:
{
"violations":[
{
"field":"getUsers.arg0",
"message":"must be greater than or equal to 0"
}
],
"status":400,
"type":"https://zalando.github.io/problem/constraint-violation",
"title":"Constraint Violation"
}
As you can see field
is equals to getUsers.arg0
which is no really user-friendly.
That why I used to create a intermediate object (DTO
?) for validation even for GET
parameters.
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
I could also imagine to put this into the javadoc of the
ConstraintViolationAdviceTrait
.@whiskeysierra about doc do you really think that this edge case should be part of
README.md
. From my point of viewREADME.md
should be an overview of the application/library/framework and not be pollute by some special case.Maybe just I can just create an issue to describe the problem (different from
BindException
support) and close it, thus using issue tracking like a kind of Q&A?