【问题标题】:Android Kotlin handling exceptions on ui thread with anko doAsyncAndroid Kotlin 使用 anko doAsync 处理 ui 线程上的异常
【发布时间】:2018-03-05 22:11:12
【问题描述】:

我是 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 不会显示。

【问题讨论】:

  • 也许这是一个愚蠢的问题,但你确定你的例外是HttpClientErrorException吗?
  • 是的,即使没有 if 吐司也不会显示。
  • 您在 LogCat 中是否有任何异常? exceptionHandler 在哪里运行,在主线程中还是在后台线程中?
  • 是的,我在 LogCat 中遇到了异常。我不确定异常处理程序是否在主线程或背景线程中运行。这是问题的一部分????
  • 我没有笔记本电脑,我会尽快更新问题。

标签: android kotlin anko


【解决方案1】:

由于异常处理程序是在后台线程中调用的,因此我在 doAsync 块中使用了 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 线程上的预期异常。欢迎反馈。

【讨论】:

    【解决方案2】:

    我也认为不应忽略(或仅记录)意外异常。但是每次使用doAsync时都加上try-canth块不是很方便。我创建了以下实用函数:

    fun <T> T.doAsyncThrowOnUI(task: AnkoAsyncContext<T>.() -> Unit) = doAsync(
            exceptionHandler = { thr -> Handler(Looper.getMainLooper()).post { throw thr }},
            task = task)
    

    它只是调用 Anko 的 doSync 并传递异常处理程序,该处理程序会在 UI 线程上重新抛出所有未处理的异常。使用doAsyncThrowOnUI 代替 Anko 的doAsync

    doAsyncThrowOnUI {
         // do something on bg thread (exceptions rethrown on ui thread)
    
         uiThread {
            // do something on ui thread
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多