@dotenvc/async-await
Version:
A minimal utility for Go-style error handling in async/await TypeScript code. Includes retries, custom error handling, and optional logging.
97 lines (68 loc) โข 2.7 kB
Markdown
for Go-style error handling in TypeScript with support for retries, custom errors, and optional logging.
- Simplifies `async/await` code by returning `[error, data]` tuples
- Optional retry logic with configurable delay
- Optional labeling for tracing/logging
- Optional custom error parser
- Fully silent by default โ no logs unless you opt in
```bash
npm install @dotenvc/async-await
yarn add @dotenvc/async-await
```
```ts
import { to } from '@dotenvc/async-await';
const [err, data] = await to(() => fetch('/api/user').then(res => res.json()));
if (err) {
console.error('Something went wrong:', err.message);
return;
}
console.log('User data:', data);
```
```ts
const [err, result] = await to(() => fetch('/api/user').then(r => r.json()), {
label: 'FetchUser',
retries: 2,
delayMs: 500,
logger: (msg, err) => console.warn(msg, err),
errorParser: (e) => new Error(`[CustomError] ${String(e)}`),
});
```
Wraps an async operation and returns a tuple `[error, data]`.
| Name | Type | Description |
|-----------------|-----------------------------------|-----------------------------------------------|
| `promiseFactory`| `() => Promise<T>` | A function returning the async operation. |
| `options` | `ToOptions` (optional) | Extra config options. |
```ts
type ToOptions = {
label?: string; // Optional name for tracing/logging
retries?: number; // Number of retry attempts on failure (default: 0)
delayMs?: number; // Delay between retries in ms (default: 100)
logger?: (msg: string, err: unknown) => void; // Optional error logger
errorParser?: (err: unknown) => Error; // Optional error transformer
};
```
- Use in API calls, background tasks, or anywhere error handling is needed.
- Great for backend logic where you want robust error control without cluttering your code with `try/catch`.
- Use with frameworks like Express, Next.js, or NestJS for consistent async error patterns.
```ts
app.get('/profile', async (req, res) => {
const [err, user] = await to(() => db.findUser(req.query.email));
if (err) {
return res.status(500).json({ error: err.message });
}
res.json(user);
});
```
MIT โ built with โค๏ธ by [@dotenv](https://github.com/dot-env)
> A minimal utility