https://github.com/iagocalazans/try2catch
A better try/catch like way to get your errors encapsulated.
https://github.com/iagocalazans/try2catch
async catch promise try trycatch
Last synced: 9 months ago
JSON representation
A better try/catch like way to get your errors encapsulated.
- Host: GitHub
- URL: https://github.com/iagocalazans/try2catch
- Owner: iagocalazans
- Created: 2023-02-24T10:43:18.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2023-04-20T19:05:11.000Z (about 3 years ago)
- Last Synced: 2025-03-28T14:01:46.285Z (about 1 year ago)
- Topics: async, catch, promise, try, trycatch
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/try2catch
- Size: 38.1 KB
- Stars: 7
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Try2Catch
A better try/catch like way to get your errors encapsulated.
## Installation
You can install Try2Catch using `npm` or `yarn`:
```bash
npm install try2catch
```
```bash
yarn add try2catch
```
## Usage
To use Try2Catch, import the Try object from the package:
```javascript
import { Try } from 'try2catch';
```
Create a Promise that resolves or rejects after some time, for example:
```javascript
const awaiter = new Promise((res, reject) => {
const random = (Math.random() * 10) + 1
setTimeout(() => {
if (random > 5) {
return res('Nice!');
}
return reject(new Error('Failed!'));
}, 5000);
});
```
An asynchronous function that uses Try to handle the Promise's result:
```javascript
const processing = async () => {
const result = await Try.promise(awaiter)
if (result.isError()) {
return result.error;
}
return result.data
}
```
In this example, `Try.promise()` takes a Promise as an argument and returns an object with a method and a property: `.isError()` and `data` or `error`. If the Promise resolves successfully, `.isError()` will be `false` and `data` will contain the resolved value. If the Promise is rejected, `.isError()` will be `true` and `error` will contain the error object.
## License
This package is licensed under the MIT license. See the LICENSE file for more details.