Kotlin中Lambda调用后deserialize无法返回成功Result的问题
问题原因与修复方案
核心问题
你的Response()函数存在逻辑漏洞:无论functionError是否为空,代码最后都会执行throw RuntimeException(error)语句。因为if分支里没有终止lambda的执行流程,哪怕进入了无错误分支执行完deserialize,后续依然会走到抛出异常的代码,导致runCatching始终捕获到异常、返回Failure,所以所有情况都会进入onFailure。
修复方案
有两种简洁的修正方式:
方式一:在无错误分支终止lambda执行
private fun InvokeResponse.Response(): Result<Response> { return runCatching { val error = this.functionError() if (error.isNullOrBlank()) { // 用return@runCatching终止lambda,直接返回反序列化结果 return@runCatching deserialize<Response>(this.payload()) } throw RuntimeException(error) } }
方式二:用else分支明确分支逻辑(更易读)
private fun InvokeResponse.Response(): Result<Response> { return runCatching { val error = this.functionError() if (error.isNullOrBlank()) { deserialize<Response>(this.payload()) } else { throw RuntimeException(error) } } }
优化建议:去掉冗余的runCatching包装
因为deserialize本身已经通过runCatching处理了反序列化异常并返回Result,所以Response()函数可以不用再嵌套runCatching,直接返回对应的Result即可:
private fun InvokeResponse.Response(): Result<Response> { val error = this.functionError() return if (error.isNullOrBlank()) { deserialize<Response>(this.payload()) } else { Result.failure(RuntimeException(error)) } }
内容的提问来源于stack exchange,提问作者CyberPunk
相关产品推荐
相关产品推荐

