https://github.com/alwalxed/catch-wrap
Type-safe error handling for sync & async TypeScript operations, no try-catch boilerplate
https://github.com/alwalxed/catch-wrap
async error-handling try-catch tyepscript
Last synced: 5 months ago
JSON representation
Type-safe error handling for sync & async TypeScript operations, no try-catch boilerplate
- Host: GitHub
- URL: https://github.com/alwalxed/catch-wrap
- Owner: alwalxed
- License: mit
- Created: 2025-09-26T06:54:19.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2025-09-26T08:33:05.000Z (6 months ago)
- Last Synced: 2025-09-26T10:24:16.051Z (6 months ago)
- Topics: async, error-handling, try-catch, tyepscript
- Language: TypeScript
- Homepage: https://npmjs.com/package/catch-wrap
- Size: 21.5 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Catch Wrap
Type-safe error handling for sync & async TypeScript operations, no try-catch boilerplate
## Features
- **Type-safe**: Full TypeScript support with proper type inference
- **Universal**: Works with sync functions, async functions, and promises
- **Zero dependencies**: Lightweight with no external dependencies
- **Consistent API**: Same interface for all operation types
- **Promise-like support**: Works with Drizzle, Prisma, and other thenable objects
## Installation
```bash
pnpm add catch-wrap
# or
bun add catch-wrap
yarn add catch-wrap
npm install catch-wrap
```
## Basic Usage
### Async Operations
```typescript
import { tryCatch } from 'catch-wrap';
const { data, error } = await tryCatch(fetch('/api/users'));
if (error) {
console.error('Failed to fetch users:', error.message);
return;
}
console.log('Status:', data.status);
const { data, error } = await tryCatch(async () => {
const response = await fetch('/api/users');
if (!response.ok) throw new Error('API request failed');
return response.json();
});
if (error) {
console.error('Operation failed:', error.message);
} else {
console.log('Users:', data);
}
```
### Synchronous Operations
```typescript
import { tryCatch } from 'catch-wrap';
const { data, error } = tryCatch(() => JSON.parse(jsonString));
if (error) {
console.error('Invalid JSON:', error.message);
return;
}
console.log('Parsed data:', data);
```
## Framework Integration
### Database Operations (Drizzle, Prisma)
Perfect for database operations that return promise-like objects:
```typescript
import { tryCatch } from 'catch-wrap';
const { data: user, error } = await tryCatch(
db.select().from(users).where(eq(users.id, userId))
);
const { data: users, error } = await tryCatch(
prisma.user.findMany({ where: { active: true } })
);
if (error) {
console.error('Database query failed:', error.message);
return [];
}
return users;
```
### File System Operations
```typescript
import fs from 'fs/promises';
import { tryCatch } from 'catch-wrap';
const { data: fileContent, error } = await tryCatch(
fs.readFile('./config.json', 'utf8')
);
if (error) {
console.error('Failed to read config file:', error.message);
return;
}
const { data: config, error: parseError } = tryCatch(() =>
JSON.parse(fileContent)
);
```
## API Reference
### `tryCatch(operation)`
A universal error handling function that wraps operations and returns a result object.
**Parameters:**
- `operation`: Can be one of:
- A `Promise`
- A function `() => T` that might throw
- A function `() => Promise` that returns a promise
**Returns:**
- For sync operations: `Result`
- For async operations: `Promise>`
**Type Parameters:**
- `T`: The expected return type of the successful operation
- `E`: The error type (defaults to `Error`)
### Types
```typescript
type Result = Success | Failure;
type Success = {
data: T;
error: null;
};
type Failure = {
data: null;
error: E;
};
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
This project is licensed under the [MIT](./LICENSE) License.