try-to-catch
DefinitelyTyped icon, indicating that this package has TypeScript declarations provided by the separate @types/try-to-catch package

3.0.1 • Public • Published

Try to Catch NPM version Build Status Coverage Status

Functional try-catch wrapper for promises.

Install

npm i try-to-catch

API

tryToCatch(fn, [...args])

Wrap function to avoid try-catch block, resolves [error, result];

Example

Simplest example with async-await:

const tryToCatch = require('try-to-catch');
const reject = Promise.reject.bind(Promise);
await tryToCatch(reject, 'hi');
// returns
// [ Error: hi]

Can be used with functions:

const tryToCatch = require('try-to-catch');
await tryToCatch(() => 5);
// returns
[null, 5];

Advanced example:

const {readFile, readdir} = require('fs/promises');
const tryToCatch = require('try-to-catch');

read(process.argv[2])
    .then(console.log)
    .catch(console.error);

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);
}

Related

License

MIT

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 3.0.1
    48,595
    • latest

Version History

Package Sidebar

Install

npm i try-to-catch

Weekly Downloads

63,477

Version

3.0.1

License

MIT

Unpacked Size

5.19 kB

Total Files

5

Last publish

Collaborators

  • coderaiser