Skip to content

Repository files navigation

Better error handling

A TypeScript utility library for elegant error handling with discriminated unions

Why This Package?

The throw keyword is not explicit about what errors a function might produce, making error handling unpredictable and hard to reason about. This package provides a type-safe alternative that makes errors part of your function signatures.

Features

  • 🔒 Type-safe error handling - No more try/catch blocks everywhere
  • 🎯 Discriminated unions - Clear distinction between success and error states
  • 🛠 Helper functions - Easy creation and manipulation of result types
  • 📦 Zero dependencies - Lightweight and focused
  • 🔥 Full TypeScript support - Complete type inference and narrowing

Quick Start

import { asData, asError, isError, type WithError } from "."

// Define a function that might fail
const divide = (
    a: number,
    b: number,
): WithError<{ data: number }, { message: string }> => {
    if (b === 0) {
        return asError({ message: "Cannot divide by zero" })
    }
    return asData({ data: a / b })
}

// Use the result
const result = divide(10, 2)

if (isError(result)) {
    console.error("Error:", result.message)
} else {
    console.log("Result:", result.data) // TypeScript knows this is a number
}

Advanced Example

import {
    asData,
    asError,
    isError,
    type ExtractError,
    type ExtractNonError,
    type WithError,
} from "better-error-handling"

type ErrorFoo = { type: "foo"; message: string }
type ErrorBar = { type: "bar"; code: number }

const fetchData = (): WithError<{ something: string }, ErrorFoo | ErrorBar> => {
    // Simulate different outcomes
    const random = Math.random()

    if (random > 0.7) {
        return asError({ type: "bar", code: 500 })
    }

    if (random > 0.4) {
        return asError({
            type: "foo",
            message: "An error of type foo occurred.",
        })
    }

    return asData({ something: "All good!" })
}

const processResult = () => {
    const result = fetchData()

    if (isError(result)) {
        if (result.type === "foo") {
            console.error("Foo error:", result.message)
            return
        }
        if (result.type === "bar") {
            console.error("Bar error with code:", result.code)
            return
        }
    }

    // TypeScript knows result.something exists here
    console.log("Success! Data:", result.something)
}

processResult()

API Reference

Types

WithError<DataType, ErrorType>

A discriminated union representing either success or error states.

ExtractNonError<Type>

Extracts the success type from a WithError type.

ExtractError<Type>

Extracts the error type from a WithError type.

Functions

asData<T>(data: T)

Creates a successful result.

asError<T>(error: T)

Creates an error result.

isError<T>(value: WithError<unknown, T>)

Type guard to check if a result represents an error.

License

MIT

About

A TypeScript utility library for elegant error handling with discriminated unions

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages