trysafely
Version:
A robust async helper to wrap promises and functions, returning [result, error] for graceful error handling.
192 lines (129 loc) โข 4.02 kB
Markdown
[](https://www.npmjs.com/package/trysafely)
[](https://opensource.org/licenses/MIT)
> A zero-dependency utility to wrap async and sync functions into predictable `{ data, err }` results โ goodbye `try...catch`, hello clarity!
------
- โ
**Eliminate try/catch boilerplate**
- ๐ **Wrap sync or async functions**
- ๐ง **Fully typed & TypeScript friendly**
- ๐ฆ **Lightweight, no dependencies**
- ๐ฏ **Predictable result shape**: `{ data: T | null, err: Error | null }`
- ๐งช **Easy testing & debugging**: No unhandled promise rejections
------
```bash
npm install trysafely
yarn add trysafely
pnpm add trysafely
```
------
> Smart wrapper for **both sync and async** functions. Determines if the function is returning a Promise, and handles errors accordingly.
```ts
import trySafely from 'trysafely';
const { data, err } = await trySafely(asyncOrSyncFn());
```
------
> Specifically wraps an **async function**, catching any thrown or rejected errors.
```ts
import { tryAsync } from 'trysafely';
const { data, err } = await tryAsync(someAsyncFunction());
```
------
> Specifically wraps a **synchronous function**, catching exceptions.
```ts
import { trySync } from 'trysafely';
const { data, err } = trySync(someSyncFunction());
```
------
```ts
import trySafely from 'trysafely';
/** Example that may return synchronously or asynchronously */
async function getUser(): Promise<string> {
await new Promise(r => setTimeout(r, 100));
if (Math.random() > 0.5) return "Alice";
throw new Error("User not found");
}
async function main() {
const { data: user, err } = await trySafely(getUser());
if (err) {
console.error("Error fetching user:", err.message);
} else {
console.log("Fetched user:", user);
}
}
```
------
```ts
import { tryAsync } from 'trysafely';
/** Simulates an async failure */
async function loadData(): Promise<number> {
throw new Error("Load failed");
}
async function run() {
const { data, err } = await tryAsync(loadData());
if (err) {
console.error("Load Error:", err.message);
} else {
console.log("Loaded:", data);
}
}
```
------
```ts
import { trySync } from 'trysafely';
/** Synchronous function that may throw */
function riskyOperation(): number {
if (Math.random() > 0.5) return 42;
throw new Error("Boom");
}
const { data, err } = trySync(riskyOperation());
if (err) {
console.error("Sync error:", err.message);
} else {
console.log("Sync result:", data);
}
```
------
Every function returns:
```ts
type TryResult<T> = {
data: T | null;
err: Error | null;
};
```
This helps keep control flow **flat and readable**, especially in concurrent or nested logic.
------
All functions are fully typed. Errors are always of type `Error`, and results are `T | null`. No more `any` surprises or missing catches.
------
- โ
Unified `trySafely` now supports both sync and async functions
- โ
Explicit `tryAsync` and `trySync` utilities included
- โ `tryPromise` deprecated โ use `trySafely(() => promise)` instead
- ๐ฆ Clean, small footprint
------
- Add optional fallback/default values in case of error
- Better error classification (e.g., custom error types, tagging)
- Performance benchmarks and tree-shaking guides
- `trysafely.allSettled()` for batches
------
## Contributing
Contributions, bug reports, and feedback are welcome!
Feel free to open an issue or PR on [GitHub](https://github.com/EllyBax/trysafely.git).
------
## License
MIT ยฉ [Elly Bax](https://github.com/EllyBax)
See LICENSE for details.