Skip to content

Resolve ElementKind.PARAMETER in ConstraintViolationExceptionHandler.createBody method #28

@Yaroslav007

Description

@Yaroslav007

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions