我是 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/