JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 15
  • Score
    100M100P100Q45873F
  • License MIT

A type-safe try-catch wrapper

Package Exports

  • @pidchashyi/try-catch

Readme

@pidchashyi/try-catch

๐Ÿงฐ Type-safe try/catch wrapper for async operations โ€” returns structured Result<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!