All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kiwiproject.jaxrs.exception.ConstraintViolationExceptionMapper Maven / Gradle / Ivy

Go to download

Kiwi is a utility library. We really like Google's Guava, and also use Apache Commons. But if they don't have something we need, and we think it is useful, this is where we put it.

There is a newer version: 4.4.0
Show newest version
package org.kiwiproject.jaxrs.exception;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.Set;

/**
 * Map {@link ConstraintViolationException} to a JSON {@link 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 {@link Response.Status} does not contain an enum constant for 422 status, * so that {@link Response.Status#fromStatusCode(int)} will return {@code null} when given 422. */ @Provider public class ConstraintViolationExceptionMapper implements ExceptionMapper { /** * We have no way to obtain the item ID from a {@link ConstraintViolationException}. Instead, we will set * it to null, which is not lovely but there's not much else we can do. */ private static final String ITEM_ID = null; /** * Convert the given {@link ConstraintViolationException} to a response containing a JSON entity. * * @param exception the exception to convert * @return a response * @see JaxrsExceptionMapper#buildResponse(JaxrsException) */ @Override public Response toResponse(ConstraintViolationException exception) { return buildResponse(exception.getConstraintViolations()); } /** * Given a set of constraint violations, build a 422 Unprocessable Entity response with a JSON entity. * * @param violations the constraint violations to convert * @return a JSON response */ public static Response buildResponse(Set> violations) { return JaxrsExceptionMapper.buildResponse(new JaxrsValidationException(ITEM_ID, violations)); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy