Skip to content

Instantly share code, notes, and snippets.

@fff
Last active November 26, 2015 15:37
Show Gist options
  • Save fff/7d364d924275003eccca to your computer and use it in GitHub Desktop.
Save fff/7d364d924275003eccca to your computer and use it in GitHub Desktop.
add json mapping exception mapper to jax ws rs Application
////
// 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