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

如何为ignoringExc方法传入自定义异常日志消息?

解决方案

1. 修改工具方法(无需改动原接口)

保留原RunnableExc接口不变,新增一个带自定义错误消息参数的ignoringExc重载方法,让它同时支持任务执行和错误提示传入:

private static void ignoringExc(RunnableExc r) {
    ignoringExc(r, "执行赋值任务时发生异常"); // 兜底默认提示
}

private static void ignoringExc(RunnableExc r, String errorMsg) {
    try {
        r.run();
    } catch (Exception e) {
        log.error(errorMsg, e); // 打印自定义消息+异常栈,方便排查问题
    }
}

@FunctionalInterface
private interface RunnableExc {
    void run() throws Exception;
}

2. 调用时传入对应字段的错误提示

在调用工具方法时,直接在第二个参数位置传入针对当前字段的自定义错误消息即可:

ignoringExc(() -> a.setAddress(b.getPerson("address")), "Person B的地址为null");
ignoringExc(() -> a.setName(b.getPerson("name")), "Person B的姓名为null");
ignoringExc(() -> a.setAge(b.getPerson("age")), "Person B的年龄为null");
// 更多字段赋值逻辑...

补充说明

  • 当b.getPerson()返回null导致setXxx()抛出空指针异常时,ignoringExc会自动捕获并打印你传入的自定义提示;
  • 日志中保留异常栈(log.error(errorMsg, e))是为了精准定位报错位置,若不需要可以简化为log.error(errorMsg)。

内容的提问来源于stack exchange,提问作者manyProblem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:05:03