2

I have a kotlinjs app. I handle a particular event (dropping of data onto a component) like this:

        onEvent {
            drop = { event ->
                GlobalScope.async {
                    //...
                    dropTask(y, data)
                }
            }
        }

// ...

    // this function has to be a suspend function because model's is
    private suspend fun dropTask(y: Int, taskId: TaskId) {
        // ... prepare data
        model.insertBefore(taskId!!, insertBefore?.id)
    }

// ... Model's function is defined like this:

    suspend fun insertBefore(taskToInsert: TaskId, taskBefore: TaskId?) {
        val (src, _) = memory.find(taskToInsert)

// ... and finally, the find function is:

    fun find(taskId: TaskId): Pair<Task?, Int> {
        // ... 
        return if (task != null) {
            // ...
        } else {          
            throw Exception("Couldn't find task with id $taskId!!")
        }
    }

The issue is that the Exception gets thrown, but isn't reported anywhere.

I have tried:

a) Installing a CoroutineExceptionHandler into the GlobalScope.async (i.e.:

                val handler = CoroutineExceptionHandler { _, e ->
                    console.log("Caught exception: $e")
                }
                GlobalScope.async(handler) {

...but this never gets called. This would be relatively clean if I could make it work. It would be even nicer if this was default behavior for kotlinjs, so that exceptions weren't accidentally unreported.

b) Calling await:

           drop = { event ->
                GlobalScope.launch {
                    GlobalScope.async() {
                        // ...
                        dropTask(y, data)
                    }.await()
                }
            }

This does result in the exception being logged to the console, but it's so ugly. It's not possible to call .await() outside of a suspend function or coroutine, so for this particular event handler I have to wrap the async call in a launch. I must be doing something wrong. Anybody have a better pattern that I should be using?

user717847
  • 695
  • 1
  • 6
  • 16

0 Answers0