0

I would like to implement @PathVariable validation therefore I created a base class for all controllers with exception handler:

  public class BaseController {
    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public RestError handleResourceNotFoundException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations ) {
            strBuilder.append(violation.getMessage());
            strBuilder.append("\n");
        }
        strBuilder.deleteCharAt(strBuilder.lastIndexOf("\n"));

        return new RestError(strBuilder.toString());
    }
}

In controllers that extend BaseController following method signature works as expected (returns {"error": invalid id}):

@PreAuthorize("hasRole('ROLE_VISA_ADMIN')")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
ResponseEntity<UserRepresentation> getUser(@Pattern(regexp = Constants.UUID_REGEX, message = "invalid id")
                                           @PathVariable String id

Whereas the same method without @PreAuthorize returns status code 500 and message: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException. As if there is no exception handler.

I'm new to spring boot so any suggestions will be highly appreciated.

Edit.

Here is the source code of the controller (it actually implements interface that describes the api):

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserController extends BaseController implements UserApi {
    private IUserService userService;

    @Override
    public ResponseEntity<UserRepresentation> getUser(@PathVariable String id) {
        UserRepresentation userRepresentation = userService.getUserRepresentationById(id);

        if (userRepresentation == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(userRepresentation, HttpStatus.OK);
        }
    }
}
makar
  • 155
  • 3
  • 14

1 Answers1

0

I know it's been a while, but I believe you're missing the @Validated annotation in your controller class.

import org.springframework.validation.annotation.Validated;

@Validated // class level
public class BaseController {
    //...
}
felipero
  • 463
  • 4
  • 13