Android Kotlin 使用 anko doAsync 在 ui 线程上处理异常

标签 android kotlin anko

我是 Kotlin 的新手,我有一个带有自定义异常处理程序的 doAsync:

doAsync(exceptionHander = {e -> handleException(e)}){
     //rest call
}

 private val handleException= {throwable : Throwable ->
        if(throwable is HttpClientErrorException){
            val response = JSONObject(throwable.responseBodyAsString)
            Toast.makeText(this, response["message"].toString(), Toast.LENGTH_LONG).show()
        }
    }

但是 Toast 从未显示。如何在 Toast 上显示此异常消息?异常处理程序是否在 ui 线程上调用?

更新:

我是这样测试的:

doAsync(exceptionHander = {e -> handleException(e)}){
      throw HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "An error has occurred")
}

使用相同的错误处理程序,但是 toast 不会显示。

最佳答案

由于异常处理程序是在后台线程中调用的,所以我在 doAsync block 中使用了 try-catch

doAsync{
     var exception: Exception? = null
     try {
          //rest call
     }
     catch(e: HttpClientErrorException){
          exception = e
     }
     uiThread {
        if (exception != null){
             // Show the exception message. 
        }
        else {
             // Update the UI with the result
        }
     }
}

因此,通过这种方式可以处理 UI 线程上的预期异常。欢迎提供反馈。

关于Android Kotlin 使用 anko doAsync 在 ui 线程上处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120350/

相关文章:

android - 应用程序无法移动到 SD 卡

android - ACRA报告中的“RAZR i”名称

android - 如何在 kotlin 中分配同名类变量?

android - Firebase 中云存储的带宽是多少?

kotlin - 在 kotlin 1.3 中使用协程的正确方法

android - Kotlin Anko自定义 View 父范围

javascript - NativeScript 中的 ClassNotFoundException 使用 .extend()

android - Kotlin 中这个简单的 var 赋值有什么问题?

android - Kotlin addTextChangeListener lambda?

javascript - Ajax 调用不适用于 android 但在 ios Cordova 上运行良好