Functional try-catch
wrapper for promises
.
npm i try-to-catch
Wrap function to avoid try-catch
block, resolves [error, result]
;
Simplest example with async-await
:
import tryToCatch from 'try-to-catch';
const reject = Promise.reject.bind(Promise);
await tryToCatch(reject, 'hi');
// returns
// [ Error: hi]
Can be used with functions:
import tryToCatch from 'try-to-catch';
await tryToCatch(() => 5);
// returns
[null, 5];
Advanced example:
import {readFile, readdir} = from 'node:fs/promises';
import tryToCatch from 'try-to-catch';
const [error, data] = await tryToCatch(read, process.argv[2]);
if (error) {
console.error(error);
process.exit(1);
}
console.log(data);
async function read(path) {
const [error, data] = await tryToCatch(readFile, path, 'utf8');
if (!error)
return data;
if (error.code !== 'EISDIR')
return error;
return await readdir(path);
}
- try-catch - functional try-catch wrapper.
MIT