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

@mcswift/safe-run

v1.0.19

Published

[English](#english) | [中文](#中文)

Readme

@mcswift/safe-run

English | 中文


中文

提供类似于 Go 语言风格的异常处理机制,避免繁琐的 try...catch 块,让你以线性的方式处理 Promise 异常和同步函数异常。

安装

npm install @mcswift/safe-run
# or
pnpm add @mcswift/safe-run

功能模块及接口文档

1. safeAwait 处理 Promise

用于捕获任意 Promise 的异常,返回一个 [error, result] 元组。如果 error 不为 null,说明发生了异常。

import { safeAwait } from "@mcswift/safe-run";

async function fetchData() {
  const [err, res] = await safeAwait(fetch("https://api.example.com/data"));
  
  if (err) {
    console.error("请求失败:", err);
    return;
  }
  
  console.log("请求成功:", res);
}

类型注释:

type SafeResult<Result> =
  | [error: null, result: Result]
  | [error: Exclude<unknown, null>, result: null];

const safeAwait: <Result = unknown>(promise: Promise<Result>) => Promise<SafeResult<Result>>;

2. safeCall 安全调用函数

用于安全地执行函数(支持同步或异步),接收散列参数,并返回 [error, result] 元组。如果函数返回 Promise,safeCall 也会返回 Promise。

import { safeCall } from "@mcswift/safe-run";

function parseJson(str: string) {
  return JSON.parse(str);
}

// 同步调用
const [err, result] = safeCall(parseJson, "invalid json");
if (err) {
  console.log("解析失败:", err);
}

// 异步调用
const [asyncErr, asyncResult] = await safeCall(async () => {
  return "async data";
});

类型注释:

function safeCall<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Result,
  ...params: Args
): SafeResult<Result>;

function safeCall<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Promise<Result>,
  ...params: Args
): Promise<SafeResult<Result>>;

3. safeApply 安全调用函数(数组传参)

与 safeCall 类似,但是参数以数组的形式传入(类似于 Function.prototype.apply)。

import { safeApply } from "@mcswift/safe-run";

function sum(a: number, b: number) {
  return a + b;
}

const [err, result] = safeApply(sum, [1, 2]);

类型注释:

function safeApply<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Result,
  params: Args
): SafeResult<Result>;

function safeApply<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Promise<Result>,
  params: Args
): Promise<SafeResult<Result>>;

English

Provides a Go-style error handling mechanism that avoids cumbersome try...catch blocks, allowing you to handle Promise exceptions and synchronous function errors in a linear fashion.

Installation

npm install @mcswift/safe-run
# or
pnpm add @mcswift/safe-run

Features & API Documentation

1. safeAwait - Handle Promises

Used to catch exceptions from any Promise, returning an [error, result] tuple. If error is not null, an exception occurred.

import { safeAwait } from "@mcswift/safe-run";

async function fetchData() {
  const [err, res] = await safeAwait(fetch("https://api.example.com/data"));
  
  if (err) {
    console.error("Request failed:", err);
    return;
  }
  
  console.log("Request succeeded:", res);
}

Type Annotations:

type SafeResult<Result> =
  | [error: null, result: Result]
  | [error: Exclude<unknown, null>, result: null];

const safeAwait: <Result = unknown>(promise: Promise<Result>) => Promise<SafeResult<Result>>;

2. safeCall - Safely Call Functions

Used to safely execute functions (supports synchronous or asynchronous), taking arguments individually and returning an [error, result] tuple. If the function returns a Promise, safeCall will also return a Promise.

import { safeCall } from "@mcswift/safe-run";

function parseJson(str: string) {
  return JSON.parse(str);
}

// Synchronous call
const [err, result] = safeCall(parseJson, "invalid json");
if (err) {
  console.log("Parsing failed:", err);
}

// Asynchronous call
const [asyncErr, asyncResult] = await safeCall(async () => {
  return "async data";
});

Type Annotations:

function safeCall<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Result,
  ...params: Args
): SafeResult<Result>;

function safeCall<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Promise<Result>,
  ...params: Args
): Promise<SafeResult<Result>>;

3. safeApply - Safely Call Functions (Array Arguments)

Similar to safeCall, but arguments are passed as an array (similar to Function.prototype.apply).

import { safeApply } from "@mcswift/safe-run";

function sum(a: number, b: number) {
  return a + b;
}

const [err, result] = safeApply(sum, [1, 2]);

Type Annotations:

function safeApply<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Result,
  params: Args
): SafeResult<Result>;

function safeApply<Args extends any[] = any[], Result extends unknown = unknown>(
  func: (...args: Args) => Promise<Result>,
  params: Args
): Promise<SafeResult<Result>>;