Skip to content

Ability to add a custom message into exception thrown by withTimeout #4628

@dant3

Description

@dant3

Sorry if this is a duplicate or superseeded by something else.

Use case
Consider the code like:

withTimeout(timeout1) {
   // some function awaiting for result
}

withTimeout(imeout2) {
   // some other awaiting logic
}

There is no way to tell which one of those thrown TimeoutCancellationException especially if the timeout value is the same. Currently the only cumbersome alternatives exist are:

try {
   withTimeout ...
} catch (ex: TimeoutCancellationException) {
    throw MyException("this is timeout1");
}

// or...

withTimeoutOrNull(timeout1) {
} ?: throw MyException("timeout1")

The Shape of the API

This could be just as simple as an optional parameter. Consider junit assertions as example: by default you can assert without any specification and when assertion fails there is not much of the specifics. However you can specify an optional parameter message and this message will be added to the AssertionError, making it easier to understand what went south. In case of kotlin coroutines stacktraces can be hard to figure out, so this becomes even more important.

Proposal

withTimeout(duration, name = "waiting for X") {
     // waiting for X
}
// produces TimeoutCancellaionException("Timed out waiting for 15000 ms: waiting for X")

Alternatively, could use CoroutineName

withTimeout(duration, context = CoroutineName("waiting for X")) {
   // waiting for X
}

// produces TimeoutCancellaionException("Coroutine(\"waiting for X\") timed out waiting for 15000 ms")

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions