|
| 1 | +# Try to Catch [![License][LicenseIMGURL]][LicenseURL] [![NPM version][NPMIMGURL]][NPMURL] [![Dependency Status][DependencyStatusIMGURL]][DependencyStatusURL] [![Build Status][BuildStatusIMGURL]][BuildStatusURL] [![Coverage Status][CoverageIMGURL]][CoverageURL] |
| 2 | + |
| 3 | +[NPMIMGURL]: https://img.shields.io/npm/v/try-to-catch.svg?style=flat |
| 4 | +[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/try-to-catch/master.svg?style=flat |
| 5 | +[DependencyStatusIMGURL]: https://img.shields.io/gemnasium/coderaiser/try-to-catch.svg?style=flat |
| 6 | +[LicenseIMGURL]: https://img.shields.io/badge/license-MIT-317BF9.svg?style=flat |
| 7 | +[NPMURL]: https://npmjs.org/package/try-to-catch "npm" |
| 8 | +[BuildStatusURL]: https://travis-ci.org/coderaiser/try-to-catch "Build Status" |
| 9 | +[DependencyStatusURL]: https://gemnasium.com/coderaiser/try-to-catch "Dependency Status" |
| 10 | +[LicenseURL]: https://tldrlegal.com/license/mit-license "MIT License" |
| 11 | + |
| 12 | +[CoverageURL]: https://coveralls.io/github/coderaiser/try-to-catch?branch=master |
| 13 | +[CoverageIMGURL]: https://coveralls.io/repos/coderaiser/try-to-catch/badge.svg?branch=master&service=github |
| 14 | + |
| 15 | +Functional `try-catch` wrapper for `promises`. |
| 16 | + |
| 17 | +## Install |
| 18 | + |
| 19 | +``` |
| 20 | +npm i try-to-catch |
| 21 | +``` |
| 22 | + |
| 23 | +## API |
| 24 | + |
| 25 | +### tryToCatch(fn, [arg1, arg2, ..., argN]) |
| 26 | + |
| 27 | +Wrap function to `await try-catch block` resolve `[error, result]`; |
| 28 | + |
| 29 | +### Example |
| 30 | + |
| 31 | +```js |
| 32 | +const fs = require('fs'); |
| 33 | +const tryCatch = require('.'); |
| 34 | +const {promisify} = require('util'); |
| 35 | +const readFile = promisify(fs.readFile); |
| 36 | +const readDir = promisify(fs.readdir); |
| 37 | + |
| 38 | +read(process.argv[2]) |
| 39 | + .then(console.log) |
| 40 | + .catch(console.error); |
| 41 | + |
| 42 | +async function read(path) { |
| 43 | + const [error, data] = await tryCatch(readFile, path, 'utf8'); |
| 44 | + |
| 45 | + if (!error) |
| 46 | + return data; |
| 47 | + |
| 48 | + if (error.code !== 'EISDIR') |
| 49 | + return error; |
| 50 | + |
| 51 | + return await readDir(path); |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +## Environments |
| 56 | + |
| 57 | +In old `node.js` environments that not fully supports `es2015`, `try-to-catch` can be used with: |
| 58 | + |
| 59 | +```js |
| 60 | +var tryToCatch = require('try-to-catch/legacy'); |
| 61 | +``` |
| 62 | + |
| 63 | +## License |
| 64 | + |
| 65 | +MIT |
| 66 | + |
0 commit comments