A simple try-catch wrapper for functions and async functions.
Install package
npm i @kreisler/try-catch
import { tryCatch, tryCatchPromise } from "@kreisler/try-catch";
or
const { tryCatch, tryCatchPromise } = require("@kreisler/try-catch");
const { tryCatch } = require('@kreisler/try-catch');
const { parse } = JSON;
const [error, result] = tryCatch(parse, 'hello');
if (error)
console.error(error.message);
(async () => {
const { readFile, readdir } = require('fs/promises');
const { tryCatchPromise } = require('@kreisler/try-catch');
const [error, data] = await tryCatchPromise(readFile, 'path', 'utf8');
if (!error){
return data;
}
if (error.code !== 'EISDIR'){
return error;
}
return await readdir('path');
})();