【发布时间】:2017-11-20 11:20:53
【问题描述】:
我在 Kotlin 项目中使用 Spring WebClient,如下所示:
data class DTO(val name: String)
@Component
class Runner: ApplicationRunner
{
override fun run(args: ApplicationArguments?)
{
try
{
val dto = get<DTO>()
}
catch (e: Exception)
{
println("ERROR, all exceptions should have been caught in 'get' ")
}
}
}
inline private fun<reified TResult: Any> get(): TResult?
{
var result: TResult? = null
try
{
result = WebClient.create("https://maps.googleapis.com/maps/api/nonexisting")
.get()
.retrieve()
.bodyToMono<TResult>()
.block()
}
catch (e: Exception)
{
println("WORKS AS EXPECTED!!")
}
return result
}
客户端将抛出异常,因为 API 将返回 404。但是异常没有被捕获到它应该在的位置,即在 get 函数的主体中,但它被传播到外部异常处理程序。
有趣的是,只有在WebClient 抛出异常时才会发生这种情况。如果我用简单的throw Exception("error") 替换try 子句中的代码,异常就会被捕获到它应该在的地方。
同样,当我将get 的签名更改为非通用 inline private fun get(): DTO? 时,问题也消失了。
对于逃避try-catch 块的异常似乎是Kotlin 工具中的一个基本错误。另一方面,这种情况只发生在WebClient 类中,这表明这是一个Spring 问题。或者,可能只是我,以错误的方式使用这些工具。
我真的很困惑,不知道如何继续。任何关于为什么会发生这种情况的想法都非常受欢迎。只是为了完整起见,这就是它在调试器中的样子:
编辑
将 Spring Boot 升级到 2.0.0.M6 后问题消失,但在 M5 中仍然存在。
所以这似乎是 Spring 问题而不是 Kotlin 问题。另一方面,了解您包含的库如何看似会导致程序违反其编写的编程语言的法律,这仍然是一件好事。
【问题讨论】:
-
如果您在 try-catch 中执行
return会发生什么? -
@Michael 问题依旧:
ERROR, all exceptions should have been caught in 'get'
标签: spring generics exception kotlin spring-webflux