Reputation: 5386
I've got a simple @RestController
. My ultimate goal is to be able to validate if an incoming @QueryParam String id
is an UUID
. That part works, but the exception being thrown by the IsValidUUIDValidator
never goes through my custom ResponseEntityExceptionHandler
. I need that to be able to control the output of the errors.
I've read and tried out a range of tutorials and blogs, but no matter what I do validation exceptions never enter GlobalExceptionHandler#handleMethodArgumentNotValid
.
Why are validation exceptions never run through handleMethodArgumentValid
in my custom ResponseEntityExceptionHandler
?
Note! I do see that Spring picks up the GlobalExceptionHandler from a simple log event in the default constructor of that class.
SearchResource
@RestController
@Path("/search")
public class SearchResource extends AbstractResource {
@GET
@Path("/suggestions")
@Produces(MediaType.APPLICATION_XML)
public Response getSuggestions(@IsValidUUID @QueryParam("territoryId") String territoryId) {
IsValidUUID
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsValidUUIDValidator.class})
public @interface IsValidUUID {
String message() default "Invalid UUID";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
isValidUUIDValidator
public class IsValidUUIDValidator implements ConstraintValidator<IsValidUUID, String> {
@Override
public void initialize(IsValidUUID constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return false;
}
try {
UUID.fromString(value);
return true;
} catch (Exception e) {
System.out.println("Invalid!");
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("The provided UUID is not valid")
.addConstraintViolation();
return false;
}
}
}
GlobalExceptionHandler
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
System.out.println("This method never gets invoked");
return super.handleMethodArgumentNotValid(ex, headers, status, request); //To change body of generated methods, choose Tools | Templates.
}
}
Upvotes: 0
Views: 1379
Reputation: 59211
ResponseEntityExceptionHandler
is a Spring MVC concept and only applies to Spring Controllers. From the look of it, your application is using Jersey. This won't apply here. You need to use the appropriate infrastructure for that in Jersey.
Upvotes: 1