You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:47:06