Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

coderaiser/try-to-catch

Open more actions menu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

63 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

Related

License

MIT

Morty Proxy This is a proxified and sanitized view of the page, visit original site.