hd-utils
Version:
A handy utils for modern JS developers
27 lines (26 loc) • 827 B
JavaScript
/**
* @description -- a function that takes a promise or a function that returns a promise and returns a promise that resolves to a Result object containing the data or error.
* @example
* const result = await tryCatch(() => {
* throw new Error('Error');
* }); // { error: Error: Error, data: null }
*
* @example
* const result = await tryCatch(() => {
* return Promise.resolve('Data');
* }); // { data: 'Data' }
*/
export default function tryCatch(arg) {
if (typeof arg === 'function') {
try {
const result = arg();
return result instanceof Promise ? tryCatch(result) : { data: result };
}
catch (error) {
return { error: error };
}
}
return arg
.then((data) => ({ data }))
.catch((error) => ({ error: error }));
}