Last active
November 26, 2015 15:37
-
-
Save fff/7d364d924275003eccca to your computer and use it in GitHub Desktop.
add json mapping exception mapper to jax ws rs Application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//// | |
// By default, there is only http 500 error for unrecognized properties against request object, | |
// without any information, it's really annoying. | |
//// | |
import javax.ws.rs.core.Response; | |
import javax.ws.rs.ext.ExceptionMapper; | |
import javax.ws.rs.ext.Provider; | |
import com.fasterxml.jackson.databind.JsonMappingException; | |
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; | |
@Provider | |
public class JsonUnrecognizedPropertyExceptionMapper implements ExceptionMapper<JsonMappingException> { | |
public Response toResponse(JsonMappingException exception) { | |
String errorMessage = "illegal JSON request"; | |
if (exception instanceof UnrecognizedPropertyException) { | |
final UnrecognizedPropertyException ex = (UnrecognizedPropertyException) exception; | |
errorMessage = String | |
.format("Unknown property: %s of object: %s", ex.getUnrecognizedPropertyName(), ex.getReferringClass().getSimpleName()); | |
} | |
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).type("text/plain").build(); | |
} | |
} | |
/////// | |
@ApplicationPath("/rest") | |
public class YourApplication extends Application { | |
@Override | |
public Set<Class<?>> getClasses() { | |
Set<Class<?>> classes = new HashSet<Class<?>>(); | |
classes.add(YourPortal.class); | |
// your other classes ... | |
classes.add(JacksonObjectMapperProvider.class); | |
classes.add(JacksonJsonProvider.class); | |
classes.add(JsonUnrecognizedPropertyExceptionMapper.class); | |
return classes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment