Proper way to handle unhandled exception


#1

Is there a proper way to catch unhandled exception?

I have made a general attempt with window.onerror (see below).
The only reported error is on non_existing_function2, but nothing is reported for the other 2 cases.

Any guidance?
Thanks

 window.onerror = { msg, url, line, col, error ->
        window.alert("Error: $msg \nurl: $url\nline: $line\ncol: $col\nerror: $error")
        true
    }
    async {
        throw Exception("generated")
    }
    async {
        js("non_existing_function1();")
    }

    js("non_existing_function2();")

#2

It seems you might be looking for CompletionHandler. You could use it like this:

async(onCompletion = { ... }) {
    throw Exception(“generated”)
}

or

async {
    throw Exception(“generated”)
}. invokeOnCompletion { ... }

Alternatively you could use a custom dispatcher like so:

val coroutineExceptionHandler = CoroutineExceptionHandler() { context, throwable -> ...  }

val dispatcher = DefaultDispatcher + coroutineExceptionHandler
    
async(dispatcher) {
    throw Exception()
}