OpenFeign调用产生UndeclaredThrowableException
为何会产生这个异常?
如何破解,拿到原始异常?
结论
OpenFeign调用 UndeclaredThrowableException 异常是被生成的动态代理类抛出来的,如果想拿到原始异常,方法有三:
- 捕获UndeclaredThrowableException后, 获取 getUndeclaredThrowable();
- 方法签名 throws 某个不希望被包装的异常 xxException;
- 提前捕获异常,转换为RuntimeException 及其子类。
查看代理类
查看代理类方法参考
// 源码
@GetMapping(value = "/tool/sleep")
Result<String> sleep(@RequestParam(value = "ms") Integer ms);
// 动态代理类 反编译结果
public final Result sleep(Integer var1) throws {
try {
return (Result)super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
可以看到 非 RuntimeException | Error 就会抛出 UndeclaredThrowableException
更进一步
查看 UndeclaredThrowableException 的介绍
Thrown by a method invocation on a proxy instance if its invocation handler's invoke method throws a checked exception (a Throwable that is not assignable to RuntimeException or Error) that is not assignable to any of the exception types declared in the throws clause of the method that was invoked on the proxy instance and dispatched to the invocation handler.
我们常常遇到的IOException能不能不被包装?
很明显,答案就在方法签名 throws 上
// 源码
@GetMapping({"/tool/sleep"})
Result<String> sleep(@RequestParam("ms") Integer ms) throws IOException;
// 动态代理类 反编译结果
public final Result sleep(Integer var1) throws IOException {
try {
return (Result)super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | IOException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
果然可行。
总结
综上,UndeclaredThrowableException 是动态代理类 在调用过程中,除了方法签名throws声明的异常类、RuntimeException 和 Error 之外的异常都会包装为 UndeclaredThrowableException 抛出。
获取原始异常,有三种方法:
- 捕获 UndeclaredThrowableException 后, 获取 getUndeclaredThrowable();
- 方法签名 throws 某个不希望被包装的异常 xxException;
- 提前捕获异常,转换为 RuntimeException 及其子类。
拓展
InvocationTargetException
当java反射调用方抛出异常时,就会用InvocationTargetException将原异常包裹;
public static Throwable unwrapThrowable(Throwable wrapped) {
Throwable unwrapped = wrapped;
while (true) {
if (unwrapped instanceof InvocationTargetException) {
unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
} else if (unwrapped instanceof UndeclaredThrowableException) {
unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
} else {
return unwrapped;
}
}
}
Reference
- https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/UndeclaredThrowableException.html

OpenFeign在调用时,除RuntimeException和Error外的异常会被包装成UndeclaredThrowableException。要获取原始异常,可捕获该异常并用getUndeclaredThrowable(),或者在方法签名中明确throws相应异常,或者转换异常为RuntimeException。InvocationTargetException在反射调用时用于包裹原异常。
2052

被折叠的 条评论
为什么被折叠?



