spring-rest-exception-handler
spring-rest-exception-handler copied to clipboard
Resolve ElementKind.PARAMETER in ConstraintViolationExceptionHandler.createBody method
We have implemented validation of primitive Spring request parameters in Controllers using @Validated annotation. Sample:
@Validated
...
@RequestMapping(path = "/listUsers", method = RequestMethod.GET)
public Page<User> listUsers(@ApiParam(value = PageRequestParameters.PAGE_DESCRIPTION) @RequestParam(name = PageRequestParameters.PAGE, required = false) @Min(PageRequestParameters.PAGE_MIN) Integer page,
@ApiParam(value = PageRequestParameters.SIZE_DESCRIPTION) @RequestParam(name = PageRequestParameters.SIZE, required = false) @Min(PageRequestParameters.SIZE_MIN) Integer size,
@ApiParam(value = PageRequestParameters.SORT_DESCRIPTION) @RequestParam(name = PageRequestParameters.SORT, required = false) String sort,
@ApiParam(value = "User name") @RequestParam(required = false) String name,
@ApiParam(value = "User enabled") @RequestParam(required = false) Boolean enabled) {
...
When validation fails - we do not get a <field> element in Error response. After debugging the sources we found this little fragment in ConstraintViolationExceptionHandler:
// path is probably useful only for properties (fields)
if (pathNode != null && pathNode.getKind() == ElementKind.PROPERTY)
After changing this to:
if (pathNode != null && (pathNode.getKind() == ElementKind.PROPERTY || pathNode.getKind() == ElementKind.PARAMETER))
We started to get a clever Error message:
<title>Validation Failed</title>
<status>422</status>
<detail>The content you've sent contains 1 validation errors.</detail>
<errors>
<errors>
<field>size</field>
<rejected>-5</rejected>
<message>must be greater than or equal to 1</message>
</errors>
</errors>
Can you add this additional check to method? Or at least make the class more extension friendly. Because currently the onyl way to fix that is to completely copy the sources and add the fix.