1.0.0 • Published 8 months ago

result-wrap v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

better-try

Type-safe error handling for TypeScript without try/catch boilerplate.

Installation

npm install better-try

Usage

Basic Usage

import { wrap, wrapAsync } from "better-try";

// Sync operations
const result = wrap(() => JSON.parse('{"id": 123}'));
if (result.success) {
  console.log(result.data.id); // 123
}

// Async operations
const result = await wrapAsync(async () => {
  const response = await fetch("api/users");
  return response.json();
});

Method Chaining

const result = wrap(() => "hello")
  .map((str) => str.length)
  .map((len) => len * 2)
  .unwrapOr(0);

Custom Error Types

enum ApiError {
  NotFound,
  Unauthorized,
}

const result = wrap<User, ApiError>(() => {
  throw ApiError.NotFound;
});

if (!result.success) {
  switch (result.error) {
    case ApiError.NotFound:
      // Handle not found
      break;
  }
}

Safe Unwrapping

// Throws if error
const data = result.unwrap();

// Returns default if error
const data = result.unwrapOr(defaultValue);

Full Example

interface User {
  id: number;
  name: string;
}

const processUser = (raw: string): Result<User> => {
  return wrap(() => JSON.parse(raw)).map((obj) => ({
    id: obj.id,
    name: obj.name.trim(),
  }));
};

const result = processUser('{"id": 1, "name": "John "}');
console.log(result.unwrapOr({ id: 0, name: "Anonymous" }));

API

  • wrap<T, E>(fn: () => T): Result<T, E>
  • wrapAsync<T, E>(fn: () => Promise<T>): Promise<Result<T, E>>
  • Result<T, E> interface with:
    • success: boolean
    • data: T | null
    • error: E | null
    • unwrap(): T
    • unwrapOr(default: T): T
    • map<U>(fn: (value: T) => U): Result<U, E>

License

MIT

1.0.0

8 months ago