InvocationTargetException异常吞噬原生异常

最近在开发中遇到了一种情况,因为使用了反射调用invoke方法之后,该方法的异常被包装成了InvocationTargetException异常,导致打印日志时只返回了以下内容

java.lang.reflect.InvocationTargetException

调用原代码:

@Override
            public Object call() throws Exception {
                Object result = null;
                Method[] methods = t.getClass().getMethods();
                for (Method m : methods) {
                    if (methodName.equalsIgnoreCase(m.getName())) {
                            result = m.invoke(t, dto);
                        }
                    }
                }
                return result;
            }

从以上代码可以看出这里invoke方法之后该方法没有做任何处理,导致外层捕获到的是InvocationTargetException

解决方式

通过捕获InvocationTargetException异常,并调用getTargetException方法获取原本抛出的异常

更改后的代码:

try {
     result = m.invoke(t, dto);
} catch (InvocationTargetException e) {
     // 获取实际目标异常
     Throwable targetException = e.getTargetException();
     log.error(methodName+"【Future】执行异常:"+targetException);
}


已发布

分类

,

来自

标签:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注