dev-plusplus / coding-docs

4 stars 2 forks source link

PATTERN: Try Catch vs Error Tuple #19

Open alacret opened 3 years ago

alacret commented 3 years ago

This is an alternative to the conventional try/catch block.

JUSTIFICATION:

let result;
try {
 result = await action();
}catch (Exception e){
     // error management
    throw e;
}

vs

import {try} from "utils";

const [result, error] = await try(action());
if ( error){
     // error management
}
/**
 * Short version of try and catch
 * @param promise
 * @param finallyFunction
 * @returns {*}
 */
exports.tryAndCatch = (promise, finallyFunction = null, throwIfError = false) => {
  return promise
    .then((result) => {
      return [result, null];
    })
    .catch((error) => {
      if (throwIfError === true) {
        throw error;
      }
      return [null, error];
    })
    .finally(() => {
      if (finallyFunction !== null) {
        if (typeof finallyFunction === 'function') {
          finallyFunction();
        }
      }
    });
};

/**
 * @param {Function | Promise} promise - Promise function to resolve.
 * @returns {Promise<[Error, undefined]|[null, object]>} Promise - Promise function to resolve.
 */
export async function handleTryCatch<T>(
  promise: (() => Promise<T>) | Promise<T> | (() => T),
): Promise<[T, undefined] | [undefined, Error]> {
  const currentPromise = typeof promise === 'function' ? promise() : promise;

  try {
    const result = await currentPromise;
    return [result, undefined];
  } catch (error: unknown) {
    return [undefined, error as Error];
  }
}