我可以自定义Jackson错误消息吗?

时间:2015-07-09 22:52:11

标签: java jackson

我已经使用了JacksonMappingException来为用户产生错误:

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;
}

除了某些类型的错误之外哪个很好,某些技术细节泄露给用户,例如类结构等,这完全是不合时宜的:

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

如果没有所有技术笨蛋,我怎能让description更像Unrecognized field \"id\"

1 个答案:

答案 0 :(得分:1)

JsonMappingException有几个子类。您可以对异常类进行instanceof检查,然后构建自己的描述。