Class ConstraintViolationExceptionMapper

  • All Implemented Interfaces:
    javax.ws.rs.ext.ExceptionMapper<javax.validation.ConstraintViolationException>

    @Provider
    public class ConstraintViolationExceptionMapper
    extends Object
    implements javax.ws.rs.ext.ExceptionMapper<javax.validation.ConstraintViolationException>
    Map ConstraintViolationException to a JSON Response.

    The mapped response has status code 422 Unprocessable Entity, which technically falls under the WebDAV extensions. See the Mozilla page on 422 Unprocessable Entity here. But in reality, many web frameworks use 422 to indicate an input validation failure, which is how we are using it here.

    It is important to note that the Response.Status does not contain an enum constant for 422 status, so that Response.Status.fromStatusCode(int) will return null when given 422.

    • Constructor Detail

      • ConstraintViolationExceptionMapper

        public ConstraintViolationExceptionMapper()
    • Method Detail

      • toResponse

        public javax.ws.rs.core.Response toResponse​(javax.validation.ConstraintViolationException exception)
        Convert the given ConstraintViolationException to a response containing a JSON entity.
        Specified by:
        toResponse in interface javax.ws.rs.ext.ExceptionMapper<javax.validation.ConstraintViolationException>
        Parameters:
        exception - the exception to convert
        Returns:
        a response
        See Also:
        JaxrsExceptionMapper.buildResponse(JaxrsException)
      • buildResponse

        public static javax.ws.rs.core.Response buildResponse​(Set<? extends javax.validation.ConstraintViolation<?>> violations)
        Given a set of constraint violations, build a 422 Unprocessable Entity response with a JSON entity.
        Parameters:
        violations - the constraint violations to convert
        Returns:
        a JSON response