try-to-catch

function try-catch wrapper for promises

MIT 15 个版本
安装
npm install try-to-catch
yarn add try-to-catch
pnpm add try-to-catch
bun add try-to-catch
README

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:

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

License

MIT

版本列表
4.0.5 2026-01-31
4.0.4 2026-01-28
4.0.3 2026-01-04
4.0.2 2025-12-31
4.0.1 2025-12-31
4.0.0 2025-12-31
3.0.1 2022-03-09
3.0.0 2020-02-24
2.0.1 2019-12-30
2.0.0 2019-10-16
1.1.1 2018-11-08
1.1.0 2018-11-08
1.0.2 2018-02-13
1.0.1 2018-02-12
1.0.0 2018-02-12