UNPKG

@queso/attempt

Version:

Wraps func in a try...catch.

33 lines (32 loc) 720 B
/** * Wraps `func` in a `try...catch`. * @param func The function to wrap. * @category Util * @returns A new wrapper function that, when called, returns a tuple of `[err, success]`. * @example function exclaim(message: string) { return message + '!' } attempt(exclaim)('hi') */ export default function attempt( /** * The function to wrap in a try...catch. */ func, ) { const wrapperName = `attempt(${func.name})` return { /** * This is a wrapper function provided by `@queso/attempt`. * The original function is called inside of a try...catch. */ [wrapperName]: (...args) => { try { return [null, func(...args)] } catch (reason) { return [reason] } }, }[wrapperName] }