npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

run-safely

v1.0.8

Published

Helpers to add better type safety and error handling to your code

Readme

Safe TypeScript Utilities

npm version Build Status

| Statements | Branches | Functions | Lines | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | Statements | Branches | Functions | Lines |

Table of Contents

A TypeScript utility package providing safe error handling patterns and typed fetch operations with Zod schema validation.

Installation

pnpm add run-safely

or

npm install run-safely

or

yarn add run-safely

Features

  • Type-safe error handling with SafeResult type
  • Safe promise/function execution with runSafe utility
  • Typed fetch operations with Zod schema validation
  • Structured error handling for HTTP requests

API Reference

SafeResult

A type representing the result of an operation that might fail, providing either an error or success value.

type SafeResult<T, E extends Error = Error> = [E] | [undefined, T];

runSafe

A utility function that safely executes promises or functions, returning a SafeResult.

function runSafe<T>(promise: Promise<T>): Promise<SafeResult<T>>;
function runSafe<T>(fn: () => T): Promise<SafeResult<T>>;
function runSafe<T>(fn: () => Promise<T>): Promise<SafeResult<T>>;

Example usage:

// With a promise
const [error, data] = await runSafe(fetchSomeData());
// With a function
const [error, result] = await runSafe(() => someOperation());

if (error) {
  console.error("Operation failed:", error);
} else {
  console.log("Success:", result);
}

fetchTyped

A type-safe fetch utility that validates response data against a Zod schema. This version throws errors that you can catch and handle.

function fetchTyped<T>(
  url: string,
  schema: z.ZodSchema<T>,
  options?: RequestInit,
): Promise<T>;

Example usage with try/catch:

import { z } from "zod";
import {
  fetchTyped,
  FetchThrewError,
  ResponseNotOkError,
  JSONParseError,
  ParseFailedError,
} from "run-safely";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

try {
  const user = await fetchTyped("/api/user/1", userSchema);
  console.log("User data:", user);
} catch (error) {
  if (error instanceof FetchThrewError) {
    console.error("Network error:", error.message);
  } else if (error instanceof ResponseNotOkError) {
    console.error("HTTP error:", error.response.status);
  } else if (error instanceof JSONParseError) {
    console.error("JSON parsing failed:", error.message);
  } else if (error instanceof ParseFailedError) {
    console.error("Invalid response data:", error.zodError);
  }
}

safeFetch

A safer version of fetchTyped that returns a SafeResult instead of throwing errors.

function safeFetch<T>(
  url: string,
  schema: z.ZodSchema<T>,
  options?: RequestInit,
): Promise<SafeResult<T, FetchError>>;

Example usage:

import { z } from "zod";
import { safeFetch } from "run-safely";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

const [error, user] = await safeFetch("/api/user/1", userSchema);

if (error) {
  switch (error.type) {
    case "FetchThrewError":
      console.error("Network error:", error.message);
      break;
    case "ResponseNotOkError":
      console.error("HTTP error:", error.response.status);
      break;
  }
  return;
}

console.log("User data:", user);

ServerActionResult

A type for representing the result of server actions with proper typing for success and error states. This is based on the suggestions from the Next docs

type ServerActionResult<T> =
  | { success: true; error?: undefined; data: T }
  | { success: false; error: string; data?: undefined };

Error Types

The package includes several error classes for structured error handling:

  • FetchError: Base error class for all fetch-related errors
  • FetchThrewError: Network or other fetch-related errors
  • ResponseNotOkError: Non-200 HTTP responses (includes the Response object)
  • JSONParseError: JSON parsing failures
  • ParseFailedError: Zod schema validation failures (includes the ZodError)

Contributing

We welcome contributions! Here's how you can help:

  1. Create your feature branch (git checkout -b feature/amazing-feature)
  2. Commit your changes (git commit -m 'Add some amazing feature')
  3. Push to the branch (git push origin feature/amazing-feature)
  4. Open a Pull Request

Please make sure to:

  • Update documentation for any new features
  • Add tests for new functionality using vitest
  • Follow the existing code style
  • Run tests before submitting (pnpm test)

License

MIT License