All files index.ts

100% Statements 41/41
100% Branches 11/11
100% Functions 4/4
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 2x 15x 13x 13x 13x 15x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 6x 6x 6x 7x  
/**
 * Represents the return type of the `betterr` and `betterrSync` functions:
 * a tuple with `data` (callback return value) and `err` (error during
 * execution), one of which will be null depending on the success of the
 * callback
 */
export type BetterrResult<TData, TError> = [TData, null] | [null, TError];
 
/**
 * Asynchronously executes the callback and returns a tuple with `data`
 * (callback return value) and `err` (error during execution), one of which
 * will be null depending on the success of the callback
 */
export const betterr = async <TData, TError extends Error = Error>(
  callback: () => TData | Promise<TData>,
): Promise<BetterrResult<TData, TError>> => {
  try {
    const data = await callback();
    return [data, null];
  } catch (error) {
    const err = error instanceof Error ? error : new Error(`${error}`);
    return [null, err as TError];
  }
};
 
/**
 * Synchronously executes the callback and returns a tuple with `data`
 * (callback return value) and `err` (error during execution), one of
 * will be null depending on the success of the callback
 */
export const betterrSync = <TData, TError extends Error = Error>(
  callback: () => TData,
): BetterrResult<TData, TError> => {
  try {
    const data = callback();
    return [data, null];
  } catch (error) {
    const err = error instanceof Error ? error : new Error(`${error}`);
    return [null, err as TError];
  }
};