@aligheisar/try-catch
v0.1.2
Published
A lightweight TypeScript utility to handle async Promises with typed try/catch results.
Downloads
219
Maintainers
Readme
@aligheisar/try-catch
A tiny utility for handling async errors without try/catch blocks.
This package wraps a promise and returns a typed, predictable result object instead of throwing, making error handling easier and more explicit.
Installation
npm install @aligheisar/try-catchor
pnpm add @aligheisar/try-catchor
yarn add @aligheisar/try-catchThe idea
JavaScript promises throw errors. This utility turns that behavior into data.
Instead of:
try {
const data = await doSomething();
} catch (err) {
// handle error
}You get:
const result = await tryCatch(doSomething());…and handle success and failure explicitly.
API
tryCatch
type TryCatchResult<T, E> =
| { success: true; data: T }
| { success: false; error: E };
function tryCatch<T, E = unknown>(
promise: Promise<T>
): Promise<TryCatchResult<T, E>>;Basic usage
import { tryCatch } from "@aligheisar/try-catch";
const result = await tryCatch(fetch("/api/user"));
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}With typed errors
type ApiError = {
message: string;
code: number;
};
const result = await tryCatch<Response, ApiError>(
fetch("/api/user")
);
if (!result.success) {
console.error(result.error.code);
}Why use this?
- No
try/catchnesting - Explicit success and failure paths
- Works well with functional or result-based patterns
- Fully typed and predictable
- Zero dependencies
