Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I customize Jackson error messages?

Tags:

java

jackson

I've got a JacksonMappingException that I'm using to produce errors for the user:

public Map<String, List<Map<String, String>>> getErrors(JsonMappingException e) {                                                                                                      

    Map<String, List<Map<String, String>>> errors = new HashMap<>();                                                                                                      

    List<Map<String, String>> badFields = new ArrayList<>();                                                                                                                  

    for (Reference ref: e.getPath()) {                                                                                                                                        
        Map<String, String> badField = new HashMap<>();                                                                                                                       
        badField.put("field", ref.getFieldName());                                                                                                                          
        badField.put("description", e.getOriginalMessage());                                                                                                                
        badFields.add(badField);                                                                                                                                              
    }                                                                                                                                                                         

    errors.put("errors", badFields);  

    return errors;
}

Which is great except for some classes of error, certain technical details leak out to the user, such as class structure, etc, that is totally unseemly:

{
  "errors" : [ {
    "field" : "id",
    "description" : "Unrecognized field \"id\" (class motif.web.resource.UserResource$PutUser), not marked as ignorable"
  } ]
}

How can I can have description be more like Unrecognized field \"id\" without all the technical mumbo jumbo?

like image 723
Dmitry Minkovsky Avatar asked Jul 09 '15 22:07

Dmitry Minkovsky


1 Answers

JsonMappingException has several subsclasses. You can do instanceof checks for the class of the exception, and then build your own description.

like image 200
tkruse Avatar answered Oct 13 '22 18:10

tkruse