如何通过HttpMessageNotReadableException返回指定字段arrival_date?
如何从HttpMessageNotReadableException中提取并返回指定字段arrival_date
实现思路
HttpMessageNotReadableException的嵌套异常中包含Jackson的InvalidFormatException,该异常提供了获取字段路径的方法,可通过它定位到出错的arrival_date字段,进而提取相关信息返回。
修改后的异常处理代码
@ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) public UnreadableSMS handleBusinessException(HttpMessageNotReadableException ex) { Throwable cause = ex.getCause(); String fieldName = null; String invalidValue = null; // 逐层遍历嵌套异常,找到InvalidFormatException while (cause != null) { if (cause instanceof InvalidFormatException) { InvalidFormatException formatEx = (InvalidFormatException) cause; // 获取字段链式路径 List<JsonMappingException.Reference> references = formatEx.getPath(); if (!references.isEmpty()) { // 取路径最后一个节点作为目标字段名 fieldName = references.get(references.size() - 1).getFieldName(); } // 获取传入的错误值 invalidValue = formatEx.getValue().toString(); break; } cause = cause.getCause(); } // 构造自定义返回对象 UnreadableSMS result = new UnreadableSMS(); if ("arrival_date".equals(fieldName)) { result.setMessage(String.format("字段%s格式错误,传入值:%s,需符合yyyy-MM-dd格式", fieldName, invalidValue)); } else { result.setMessage("请求参数格式错误"); } return result; }
关键代码说明
- 嵌套异常遍历:HttpMessageNotReadableException的直接触发原因是Jackson解析异常,需逐层获取嵌套异常直到找到
InvalidFormatException - 字段路径提取:通过
formatEx.getPath()获取字段的链式引用路径,取最后一个节点即可得到具体出错的字段名 - 针对性返回:判断字段为
arrival_date时,返回包含字段名和错误值的提示信息,前端可直接定位问题字段
注意事项
- 确保自定义返回类
UnreadableSMS包含对应的消息属性及setter方法 - 若需兼容其他字段的解析错误,可扩展逻辑覆盖更多场景
内容的提问来源于stack exchange,提问作者SANSONAN
相关产品推荐
相关产品推荐

