Package Exports
- @pidchashyi/try-catch
Readme
@pidchashyi/try-catch
๐งฐ Type-safe
try/catchwrapper for async operations โ returns structuredResult<T, E>objects instead of throwing errors.
Eliminate unhandled exceptions and simplify async error handling with a clean, typed interface. Features optional logging, lifecycle hooks, and full type inference.
๐ฆ Installation
npm install @pidchashyi/try-catchโ๏ธ API Overview
Result<T, E>
type Result<T, E = Error> = Success<T> | Failure<E>;Success<T>:{ status: "success"; data: T; error: null }Failure<E>:{ status: "failure"; data: null; error: E }
Type Guards
isSuccess(result): result is Success<T>;
isFailure(result): result is Failure<E>;๐ง Usage
Basic Example
import { tryCatch, isSuccess, isFailure } from "@pidchashyi/try-catch";
const result = await tryCatch(
fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json()),
{
select: (data) => data.map((user) => user.name),
}
);
if (isSuccess(result)) {
console.log("User names:", result.data);
} else {
console.error("Failed to fetch user names:", result.error);
}๐ ๏ธ With Options
const result = await tryCatch(fetchData(), {
logError: true,
onError: (err) => {
// custom error reporting
reportToService(err);
},
onFinally: () => {
// disable loading
setIsLoading(false);
},
});๐งช Type Guards
if (isSuccess(result)) {
// result.data is strongly typed and non-null
} else if (isFailure(result)) {
// result.error is strongly typed and non-null
}๐งฐ API Reference
tryCatch(promise, options?)
Wraps any async function or promise and returns a typed Result<T, E> object.
Parameters:
| Name | Type | Description |
|---|---|---|
promise |
Promise<T> |
Async operation to wrap |
options |
TryCatchOptions<E> & { select?: (data: T) => S } |
Optional callbacks and selector |
Returns:
Promise<Result<S, E>>;TryCatchOptions<E>
| Option | Type | Description |
|---|---|---|
logError |
boolean |
Logs error to console if true |
onError |
(error: E) => void |
Optional custom error handler |
onFinally |
() => void |
Called regardless of success/failure |
select |
(data: T) => S |
Selector function to transform data |
๐ก๏ธ Safeguards & Features
โ
Fully typed Success<T> / Failure<E>
โ
Catches unknown errors and casts to Error
โ
Optional error logger and lifecycle hooks
โ
Helps enforce non-throwing API patterns
โ No global side effects
โ No dependency on specific frameworks
๐ค Author
Built with safety-first philosophy by Pidchashyi
๐ License
MIT ยฉ LICENSE
If you want, I can also help generate a package.json or prepare other docs!