https://github.com/itsezz/try-catch
A lightweight TypeScript utility that transforms error handling with type-safe Result patterns, making your code cleaner and more predictable.
https://github.com/itsezz/try-catch
error-handling result-pattern try-catch typescript utility
Last synced: about 1 month ago
JSON representation
A lightweight TypeScript utility that transforms error handling with type-safe Result patterns, making your code cleaner and more predictable.
- Host: GitHub
- URL: https://github.com/itsezz/try-catch
- Owner: itsEzz
- License: mit
- Created: 2025-05-20T18:25:59.000Z (10 months ago)
- Default Branch: master
- Last Pushed: 2026-02-02T06:34:09.000Z (about 1 month ago)
- Last Synced: 2026-02-02T18:30:43.403Z (about 1 month ago)
- Topics: error-handling, result-pattern, try-catch, typescript, utility
- Language: TypeScript
- Homepage:
- Size: 421 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @itsezz/try-catch
[](https://npmjs.com/package/@itsezz/try-catch)
Type-safe error handling for TypeScript. No more `try/catch` blocks.
## Install
```bash
npm install @itsezz/try-catch
```
## Result Types
```typescript
type Result = Success | Failure;
type Success = { data: T; error?: never; ok: true };
type Failure = { data?: never; error: E; ok: false };
```
Use `result.ok` to check success/failure with full TypeScript narrowing.
## Quick Start
```typescript
import { tryCatch, isError } from '@itsezz/try-catch';
// Sync
const result = tryCatch(() => JSON.parse('{"name":"user"}'));
if (result.ok) console.log(result.data.name); // "user"
else console.error(result.error);
// Async
const user = await tryCatch(fetch('/api/user').then(r => r.json()));
if (isError(user)) return null;
return user.data;
```
## API
### Functions
| Function | Short alias | Returns | Description |
| ----------------- | ----------- | --------------------------- | ----------------------- |
| `tryCatch()` | `t()` | `Result \| Promise` | Auto-detects sync/async |
| `tryCatchSync()` | `tc()` | `Result` | Guaranteed sync |
| `tryCatchAsync()` | `tca()` | `Promise` | Guaranteed async |
> **Note**: `tryCatch` may not correctly infer if the result is `Promise>` or `Result` in certain conditions and defaults to `Promise>` when unsure. Use explicit variants for guaranteed type safety.
### Create Results
```typescript
success(42) // { data: 42, ok: true }
failure('err') // { error: 'err', ok: false }
```
### Check Results
```typescript
if (result.ok) result.data; // Success
else result.error; // Failure
isSuccess(result); // type guard
isError(result); // type guard
```
### Transform Results
```typescript
map(result, fn) // transform success value
flatMap(result, fn) // chain operations returning Result
unwrapOr(result, default) // get value or default
unwrapOrElse(result, fn) // get value or compute from error
match(result, { // pattern matching
success: (data) => ...,
failure: (error) => ...
})
```
## Examples
### Safe JSON Parsing
```typescript
const json = tryCatch(() => JSON.parse(input));
if (!json.ok) return { error: 'Invalid JSON' };
return json.data;
```
### API Request with Type Safety
```typescript
interface User {
id: number;
name: string;
}
const fetchUser = async (): Promise => {
const result = await tryCatch(fetch('/api/user').then(r => r.json()));
if (result.ok) return result.data;
return null;
};
```
### Validation
```typescript
const validate = (input: unknown): Result => {
const parsed = tryCatch(() => JSON.parse(input as string));
if (!parsed.ok) return failure(['Invalid JSON']);
const errors: string[] = [];
if (!parsed.data.name) errors.push('Name required');
return errors.length > 0 ? failure(errors) : success(parsed.data);
};
```
### Functional Pipeline
```typescript
const result = unwrapOr(
flatMap(success('42'), s => success(parseInt(s))),
0
); // 84
```
## FAQ
**Default error type?** `Error`. Use generics for custom types:
```typescript
tryCatch(() => fetchData())
```
**When to use each variant?**
- `tryCatch`: Don't care about sync/async distinction
- `tryCatchSync`: Need guaranteed sync return
- `tryCatchAsync`: Need guaranteed `Promise` return
## License
MIT