Last active
August 17, 2024 09:56
-
-
Save typeofweb/60d8c05a645865a0f24d8705b2c38607 to your computer and use it in GitHub Desktop.
Turn async values and errors into tuples. https://www.npmjs.com/package/safe-try
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Also available on NPM: https://www.npmjs.com/package/safe-try | |
// By @typeofweb 2024 | |
// License: MIT | |
type PromiseToTupleResult<T> = [Error, null] | [null, Awaited<T>]; | |
export const try_ = async <T extends Promise<unknown>>( | |
promise: T, | |
): Promise<PromiseToTupleResult<T>> => { | |
try { | |
const result = await promise; | |
return [null, result]; | |
} catch (maybeError) { | |
// You could change the logic here to handle errors in a more sophisticated way maybe? | |
const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); | |
return [error, null]; | |
} | |
}; | |
// usage | |
const [result, error] = await try_(asyncMightFail()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment