Open alacret opened 3 years ago
This is an alternative to the conventional try/catch block.
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]; } }
This is an alternative to the conventional try/catch block.
JUSTIFICATION:
vs