All files / app/utils safe-await.ts

100% Statements 15/15
100% Branches 3/3
100% Functions 6/6
100% Lines 13/13

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      1x             6x     3x 15x       1x 5x   3x 1x 1x   2x     2x 1x     5x      
// TypeScript port of https://github.com/DavidWells/safe-await/
 
// Native Error types https://mzl.la/2Veh3TR
const nativeExceptions = [
  EvalError,
  RangeError,
  ReferenceError,
  SyntaxError,
  TypeError,
  URIError,
].filter(except => typeof except === 'function');
 
function throwNative(error: Error) {
  for (const Exception of nativeExceptions) {
    if (error instanceof Exception) throw error;
  }
}
 
export function safeAwait<T>(promise: Promise<T>, finallyFn?: () => void) {
  return promise
    .then(data => {
      if (data instanceof Error) {
        throwNative(data);
        return [data] as readonly [Error];
      }
      return [undefined, data] as const;
    })
    .catch((error: Error) => {
      throwNative(error);
      return [error] as const;
    })
    .finally(() => {
      if (finallyFn) finallyFn();
    });
}