首页 > 解决方案 > 如何使用改造 + 协程处理错误响应

问题描述

我是协程的新手。本教程尝试使用改造 + 协程 + Jake Wharton 的 CoroutineCallAdapterFactory

但是不知道如何处理 json 响应错误。例如错误可能是这样的:

{
  "code": 105,
  "error": "invalid field name: bl!ng"
} 

我认为在TmdbMovie类中添加代码错误字段(并检查空字段的对象)- 这是错误的。然后 - 在TmdbViewModel中启动协程后如何使用错误字段?

标签: androidkotlinretrofitcoroutine

解决方案


try/catchawait正如@JakeWharton 在本期中推荐的那样

try {
    youService().await()
} catch(ex: HttpException) {
    // do your handling here
}

推荐阅读