Try-catch oneliner

There is always an option to return a third item in the array that informs you whether or not it was an error or a result.

const [err, result, wasError] = Function.try(...)

That way, if you don't care about the third value, you can just ignore it.

// Remaining elements are automatically ignored
const [err, result] = Function.try(...)

Another thing to remember, is that you don't have to destructure the values at that spot if we're going the object route. This is currently my prefered way of working with this sort of system:

const maybeUserId = Promise.try(() => createUser(...))
if (maybeUserId.status === 'ERROR') { /* handle error */ }
const userId = maybeUserId.value
/* Continue the "happy path" */

This makes it easier to deal with the scenario that you might be using Promise.try() multiple times in the same function.

1 Like