An open API service indexing awesome lists of open source software.

https://github.com/oda2/using-try-catch

Simplify the use of try-catch
https://github.com/oda2/using-try-catch

await promise try-catch try-catch-js typescript

Last synced: 4 months ago
JSON representation

Simplify the use of try-catch

Awesome Lists containing this project

README

          


using-try-catch

using-try-catch




npm version


npm downloads


tests


license

> A tiny utility that simplifies try-catch handling in JavaScript/TypeScript. No more repetitive try-catch blocks for every async operation.

## Why?

Handling errors with async/await often leads to verbose code:

```js
const fetchData = async () => {
let data;
let error;

try {
data = await api.get('/user');
} catch (err) {
error = err;
}

if (error) return handleError(error);
return processData(data);
};
```

## Quick Start

```bash
npm install using-try-catch
```

```js
import usingTryCatch from 'using-try-catch';

const fetchData = async () => {
const { data, error } = await usingTryCatch(api.get('/user'));

if (error) return handleError(error);
return processData(data);
};
```

That's it! Returns `{ data, error }` - always.

## Features

- **Zero dependencies** - Ultra lightweight
- **TypeScript support** - Fully typed out of the box
- **Universal** - Works in Node.js and browsers
- **Flexible** - Handles single or multiple promises

## Usage

### Single Promise

```js
const { data, error } = await usingTryCatch(fetchUser());

if (error) {
console.log('Failed:', error.message);
return;
}

console.log('User:', data.name);
```

### Multiple Promises (Parallel)

```js
const { data, error } = await usingTryCatch([
fetchUser(),
fetchPosts(),
fetchComments()
]);

if (error) {
console.log('One or more requests failed');
return;
}

const [user, posts, comments] = data;
```

## API

```ts
usingTryCatch(promise: Promise | Promise[]): Promise<{
data: T | T[] | null;
error: unknown;
}>
```

- Returns an object with `data` and `error` properties
- `error` is `null` on success, unknown on failure
- Works with single promises or arrays of promises

## TypeScript

Fully typed out of the box:

```ts
import usingTryCatch from 'using-try-catch';

const { data, error } = await usingTryCatch(fetchUser());
// data is typed as User | User[] | null
// error is typed as unknown
```

## Requirements

- Node.js >= 18

## Browser

Load via CDN:

```html

const { data, error } = await usingTryCatch(fetch('/api/data'));

```

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.


issues

## License

MIT - See [LICENSE](LICENSE) for details.

---


Made with ❤️ by Renato Oda