Half_Duplex
Half_Duplex

Reputation: 5234

Jersey bean validation - return validation message for bad requests

Is it possible to return a validation annotations message in the response for bad responses? I thought this was possible but I have noticed that our projects are not given detailed bad request messages.

@NotNull(message="idField is required")
@Size(min = 1, max = 15) 
private String idField;

I'd like to see "idField is required" returned if a request is made that's missing the idField. I am using jersey 2.0. What I'm seeing for a response is this...

{
  "timestamp": 1490216419752,
  "status": 400,
  "error": "Bad Request",
  "message": "Bad Request",
  "path": "/api/test"
}

Upvotes: 2

Views: 2968

Answers (2)

mxb
mxb

Reputation: 3330

Building upon Justin response, here it is a version that uses Java 8 stream API:

@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException e) {
        List<String> messages = e.getConstraintViolations().stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.toList());

        return Response.status(Status.BAD_REQUEST).entity(messages).build();
    }

}

Upvotes: 1

Justin Jose
Justin Jose

Reputation: 2171

It looks like your Bean validation exception(ConstraintViolationException) is translated by one of your ExceptionMappers. You can register an ExceptionMapper for ConstraintViolationException as shown below and return data in the format you want. ConstraintViolationException has all the information you are looking for.

@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

  @Override
  public Response toResponse(ConstraintViolationException e) {
    // There can be multiple constraint Violations
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    List<String> messages = new ArrayList<>();
    for (ConstraintViolation<?> violation : violations) {
        messages.add(violation.getMessage()); // this is the message you are actually looking for

    }
    return Response.status(Status.BAD_REQUEST).entity(messages).build();
  }

}

Upvotes: 9

Related Questions