Search code examples
androidkotlinanko

Android Kotlin handling exceptions on ui thread with anko doAsync


I am new to Kotlin and I have this doAsync with a custom exception handler:

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()
        }
    }

However the Toast is never shown. How can I show this exception message on a Toast? Is the exception handler called on the ui thread?

Update:

I have tested this way:

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

with the same error handler, however the toast won't show.


Solution

  • Since the exception handler is called in a background thread, I used a try-catch in the doAsync bloc.

    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
            }
         }
    }
    

    So this way one can handle the expected exception on the UI thread. Feedback is welcome.