https://github.com/dsnchz/try-catch
Simple try-catch utility function for JavaScript
https://github.com/dsnchz/try-catch
try-catch try-catch-wrapper utility-function utility-library
Last synced: 3 months ago
JSON representation
Simple try-catch utility function for JavaScript
- Host: GitHub
- URL: https://github.com/dsnchz/try-catch
- Owner: dsnchz
- License: mit
- Created: 2025-05-08T16:16:37.000Z (9 months ago)
- Default Branch: main
- Last Pushed: 2025-06-05T17:14:16.000Z (8 months ago)
- Last Synced: 2025-09-18T11:04:32.333Z (4 months ago)
- Topics: try-catch, try-catch-wrapper, utility-function, utility-library
- Language: TypeScript
- Homepage:
- Size: 83 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# @dschz/try-catch
[](LICENSE)
[](https://www.npmjs.com/package/@dschz/try-catch)
[](https://bundlephobia.com/package/@dschz/try-catch)
[](https://jsr.io/@dschz/try-catch)
[](https://github.com/dsnchz/try-catch/actions/workflows/ci.yaml)
> A tiny utility to wrap promises or async functions and return a `[error, data]` tuple — no more `try/catch` boilerplate.
## ✨ Features
- ✅ Supports both async functions and raw promises
- ✅ Catches both **sync and async** errors
- ✅ Strongly typed result via `Result`
- ✅ Zero dependencies — just TypeScript
## 📆 Installation
```bash
npm install @dschz/try-catch
pnpm install @dschz/try-catch
yarn install @dschz/try-catch
bun install @dschz/try-catch
```
## 🚀 Usage
### Wrapping a promise result
```ts
import { tryCatch } from "@dschz/try-catch";
const [err, res] = await tryCatch(fetch("/api/data"));
```
### Wrapping an async function
```ts
const [err, user] = await tryCatch(() => fetchUserById(123));
```
### Wrapping a sync function that might throw
```ts
const [err, parsed] = await tryCatch(() => JSON.parse('{"valid":true}'));
if (err) {
console.error("Invalid JSON:", err.message);
}
```
## Note
⚠️ Always wrap expressions that might throw in a function.
This ensures the error is caught inside the try-catch scope.
```ts
// ✅ CORRECT
await tryCatch(() => JSON.parse("{ malformed }"));
// ❌ INCORRECT — throws before tryCatch is even called
await tryCatch(JSON.parse("{ malformed }"));
```
## 🧠 Types
```ts
type Success = [error: null, data: T];
type Failure = [error: E, data: null];
type Result = Success | Failure;
```
The return value is a tuple:
```ts
[error, data]; // One will always be null
```
## 🧪 Example with Custom Error Types
```ts
class MyError extends Error {
constructor(message: string) {
super(message);
this.name = "MyError";
}
}
const [err, data] = await tryCatch(() => doSomething());
```
## 📄 License
MIT © [Daniel Sanchez](https://github.com/thedanchez)