README
tc
destructurable, async-friendly try...catch
wrapper function with support for error side effects and fallback values
Installation
yarn add @replygirl/tc
Usage
Basic
import tc from '@replygirl/tc'
const [x] = await tc(async () => true)
console.info(x) // true
const [y, e] = await tc(async () => { throw new Error() })
console.info(y ?? e) // Error
tcs
(no Promises or async/await)
Sync variant: import { tc } from '@replygirl/tc'
const [x] = tc(() => true)
console.info(x) // true
const [y, e] = tc(() => { throw new Error() })
console.info(y ?? e) // Error
Custom error handling
await tc(
async() => { throw new Error() },
async e => console.error(e)
) // Error
Returning fallback values in error handlers
const [y] = await tc(
async () => { throw new Error() },
async e => false
)
console.info(y) // false
TypeScript
If you need to override the inferred return type of your callback or error handler (let's say your error handler returns void
instead of matching your callback), tc
and tcs
both accept T
and U
parameters that represent the unwrapped values of each:
declare function tc <T = unknown, U = T>(
cb: () => Promise<T>,
fb?: (e?: unknown) => Promise<U>
): Promise<[(T | U)?, unknown?]>
declare function tcs <T = unknown, U = T>(
cb: () => T,
fb?: (e?: unknown) => U
): [(T | U)?, unknown?]