How can I catch an exception in Kotlin coroutine when I am awaiting it in another function?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















Sorry for the vague title, couldn't come up with something better.



So I read this article and wanted to do the same. problem is that I can't do try { promise... } catch (e) { } cause the error gets swallowed. I can catch the error where I await it, but I don't want that.



and my code looks like this:



typealias Promise<T> = Deferred<T>

fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.async(Dispatchers.Main) {
// using try/catch here works but I don't want it here.
val result = this@then.await()
handler.invoke(result)
}

object PromiseUtil {
fun <T> promisify(block: suspend CoroutineScope.() -> T): Promise<T> = GlobalScope.async { block.invoke(this) }
}

// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


And I read this and this one too, but I want to somehow catch errors in the UI code, and don't want to use runBlocking { ... }.



Thanks.










share|improve this question























  • On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

    – shkschneider
    Jan 4 at 15:53











  • @shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

    – Pooya
    Jan 4 at 16:40


















0















Sorry for the vague title, couldn't come up with something better.



So I read this article and wanted to do the same. problem is that I can't do try { promise... } catch (e) { } cause the error gets swallowed. I can catch the error where I await it, but I don't want that.



and my code looks like this:



typealias Promise<T> = Deferred<T>

fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.async(Dispatchers.Main) {
// using try/catch here works but I don't want it here.
val result = this@then.await()
handler.invoke(result)
}

object PromiseUtil {
fun <T> promisify(block: suspend CoroutineScope.() -> T): Promise<T> = GlobalScope.async { block.invoke(this) }
}

// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


And I read this and this one too, but I want to somehow catch errors in the UI code, and don't want to use runBlocking { ... }.



Thanks.










share|improve this question























  • On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

    – shkschneider
    Jan 4 at 15:53











  • @shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

    – Pooya
    Jan 4 at 16:40














0












0








0








Sorry for the vague title, couldn't come up with something better.



So I read this article and wanted to do the same. problem is that I can't do try { promise... } catch (e) { } cause the error gets swallowed. I can catch the error where I await it, but I don't want that.



and my code looks like this:



typealias Promise<T> = Deferred<T>

fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.async(Dispatchers.Main) {
// using try/catch here works but I don't want it here.
val result = this@then.await()
handler.invoke(result)
}

object PromiseUtil {
fun <T> promisify(block: suspend CoroutineScope.() -> T): Promise<T> = GlobalScope.async { block.invoke(this) }
}

// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


And I read this and this one too, but I want to somehow catch errors in the UI code, and don't want to use runBlocking { ... }.



Thanks.










share|improve this question














Sorry for the vague title, couldn't come up with something better.



So I read this article and wanted to do the same. problem is that I can't do try { promise... } catch (e) { } cause the error gets swallowed. I can catch the error where I await it, but I don't want that.



and my code looks like this:



typealias Promise<T> = Deferred<T>

fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.async(Dispatchers.Main) {
// using try/catch here works but I don't want it here.
val result = this@then.await()
handler.invoke(result)
}

object PromiseUtil {
fun <T> promisify(block: suspend CoroutineScope.() -> T): Promise<T> = GlobalScope.async { block.invoke(this) }
}

// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


And I read this and this one too, but I want to somehow catch errors in the UI code, and don't want to use runBlocking { ... }.



Thanks.







android kotlin kotlinx.coroutines






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 15:40









PooyaPooya

2928




2928













  • On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

    – shkschneider
    Jan 4 at 15:53











  • @shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

    – Pooya
    Jan 4 at 16:40



















  • On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

    – shkschneider
    Jan 4 at 15:53











  • @shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

    – Pooya
    Jan 4 at 16:40

















On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

– shkschneider
Jan 4 at 15:53





On your UI I think you should use the other extensions thenAsync for the await() to be done correctly.

– shkschneider
Jan 4 at 15:53













@shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

– Pooya
Jan 4 at 16:40





@shkschneider tested that but it didn't work, and most of the time I don't have other asynchronous work to do after first one.

– Pooya
Jan 4 at 16:40












1 Answer
1






active

oldest

votes


















2














The exception is never caught because it's never propagated by the async call. That happens when await() is called.



See coroutine exception handling.



Your code should be:



// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


But this won't compile as await() is a suspending function. Therefore, it should be more like:



// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("ERROR_TAG", "It will catch error here")
throwable.printStackTrace()
}) {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}





share|improve this answer
























  • Thanks. I thought awaiting it in "then function" will do that.

    – Pooya
    Jan 4 at 20:44












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54042034%2fhow-can-i-catch-an-exception-in-kotlin-coroutine-when-i-am-awaiting-it-in-anothe%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














The exception is never caught because it's never propagated by the async call. That happens when await() is called.



See coroutine exception handling.



Your code should be:



// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


But this won't compile as await() is a suspending function. Therefore, it should be more like:



// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("ERROR_TAG", "It will catch error here")
throwable.printStackTrace()
}) {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}





share|improve this answer
























  • Thanks. I thought awaiting it in "then function" will do that.

    – Pooya
    Jan 4 at 20:44
















2














The exception is never caught because it's never propagated by the async call. That happens when await() is called.



See coroutine exception handling.



Your code should be:



// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


But this won't compile as await() is a suspending function. Therefore, it should be more like:



// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("ERROR_TAG", "It will catch error here")
throwable.printStackTrace()
}) {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}





share|improve this answer
























  • Thanks. I thought awaiting it in "then function" will do that.

    – Pooya
    Jan 4 at 20:44














2












2








2







The exception is never caught because it's never propagated by the async call. That happens when await() is called.



See coroutine exception handling.



Your code should be:



// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


But this won't compile as await() is a suspending function. Therefore, it should be more like:



// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("ERROR_TAG", "It will catch error here")
throwable.printStackTrace()
}) {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}





share|improve this answer













The exception is never caught because it's never propagated by the async call. That happens when await() is called.



See coroutine exception handling.



Your code should be:



// somewhere in my UI testing it.
try {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}


But this won't compile as await() is a suspending function. Therefore, it should be more like:



// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("ERROR_TAG", "It will catch error here")
throwable.printStackTrace()
}) {
PromiseUtil.promisify { throw Exception("some exp") }
.then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 4 at 17:02









veritas1veritas1

4,65741632




4,65741632













  • Thanks. I thought awaiting it in "then function" will do that.

    – Pooya
    Jan 4 at 20:44



















  • Thanks. I thought awaiting it in "then function" will do that.

    – Pooya
    Jan 4 at 20:44

















Thanks. I thought awaiting it in "then function" will do that.

– Pooya
Jan 4 at 20:44





Thanks. I thought awaiting it in "then function" will do that.

– Pooya
Jan 4 at 20:44




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54042034%2fhow-can-i-catch-an-exception-in-kotlin-coroutine-when-i-am-awaiting-it-in-anothe%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas