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

@arctics/graceful-executor

v1.1.0

Published

A robust utility for safely executing async functions with centralized error handling and fallback values.

Readme

@arctics/graceful-executor

license npm latest package npm downloads Checks Build CI install size npm bundle size Known Vulnerabilities

Table of Contents

  1. Introduction
  2. Features
  3. Installation
  4. Usage
  5. Examples
  6. API Reference
  7. Contributing
  8. License

Introduction

Tired of writing repetitive try...catch blocks? 😫 @arctics/graceful-executor is a lightweight, zero-dependency TypeScript utility that simplifies error handling for both synchronous and asynchronous functions.

It provides a clean, consistent way to execute functions, returning a predictable [error, result] tuple that eliminates boilerplate code and makes your logic cleaner and more robust.

Features

  • Centralized Error Handling: Configure a global error handler and a default return value for your entire application.
  • Retries with Delay: Automatically retry failed operations with configurable retry counts and delays.
  • Timeout Support: Abort long-running operations with a configurable timeout.
  • Logging: Enable detailed logs for successful executions, errors, and retries.
  • Batch Execution: Execute multiple functions in parallel and handle their results collectively.
  • Per-Call Overrides: Easily override global settings with specific options for individual function calls.
  • Built-in Finally: Use the optional finally callback for guaranteed cleanup actions.
  • TypeScript-First: Built with strong types to provide a safe and predictable development experience.
  • Universal: Works seamlessly with both async and synchronous functions.

Installation

npm install @arctics/graceful-executor

or

yarn add @arctics/graceful-executor

Usage

Importing the Library

The library supports both CommonJS and ES Modules:

  • CommonJS:

    const {
      safeExecute,
      configureSafeExecute,
    } = require('@arctics/graceful-executor');
  • ES Modules:

    import {
      safeExecute,
      configureSafeExecute,
    } from '@arctics/graceful-executor';

Configuration

You can configure global behavior for safeExecute using configureSafeExecute. This allows you to set a global error handler and a default fallback value.

import { configureSafeExecute } from '@arctics/graceful-executor';

configureSafeExecute({
  errorHandler: (error) => console.error('Global Error:', error),
  defaultValue: 'default value',
});

Examples

Synchronous Example

import { safeExecute } from '@arctics/graceful-executor';

function syncFunction() {
  if (Math.random() > 0.5) {
    throw new Error('Random sync error');
  }
  return 'Sync success';
}

const [error, result] = safeExecute(syncFunction);

if (error) {
  console.error('Sync Error:', error.message);
} else {
  console.log('Sync Result:', result);
}

Asynchronous Example

import { safeExecute } from '@arctics/graceful-executor';

async function asyncFunction() {
  if (Math.random() > 0.5) {
    throw new Error('Random async error');
  }
  return 'Async success';
}

(async () => {
  const [error, result] = await safeExecute(asyncFunction);

  if (error) {
    console.error('Async Error:', error.message);
  } else {
    console.log('Async Result:', result);
  }
})();

Retry Logic

import { safeExecute } from '@arctics/graceful-executor';

let attempt = 0;
function retryFunction() {
  attempt++;
  if (attempt < 3) {
    throw new Error('Retry error');
  }
  return 'Success after retries';
}

const [error, result] = await safeExecute(retryFunction, {
  retries: 2,
  retryDelay: 1000, // 1 second delay between retries
});

console.log('Error:', error);
console.log('Result:', result);

Timeout Support

import { safeExecute } from '@arctics/graceful-executor';

async function longRunningFunction() {
  await new Promise((resolve) => setTimeout(resolve, 5000)); // Simulate a 5-second delay
  return 'Completed';
}

const [error, result] = await safeExecute(longRunningFunction, {
  timeout: 3000, // 3-second timeout
});

console.log('Error:', error); // Logs timeout error
console.log('Result:', result); // Logs null

Logging

import { safeExecute } from '@arctics/graceful-executor';

function exampleFunction() {
  return 'Logging example success';
}

const [error, result] = await safeExecute(exampleFunction, {
  logging: true, // Enable logging
});

Batch Execution

import { safeExecuteBatch } from '@arctics/graceful-executor';

async function task1() {
  return 'Task 1 completed';
}

async function task2() {
  throw new Error('Task 2 failed');
}

async function task3() {
  return 'Task 3 completed';
}

const results = await safeExecuteBatch([task1, task2, task3]);

console.log(results);
// Output:
// [
//   [null, 'Task 1 completed'],
//   [Error: Task 2 failed, null],
//   [null, 'Task 3 completed']
// ]

API Reference

safeExecute(fn, options?)

Safely executes a function and returns a tuple [error, result].

  • Parameters:

    • fn: The function to execute (can be synchronous or asynchronous).
    • options (optional): An object with the following properties:
      • errorHandler: A custom error handler for this specific call.
      • defaultValue: A fallback value to return if an error occurs.
      • finally: A callback function to execute after the operation.
      • retries: Number of retry attempts if the function fails.
      • retryDelay: Delay (in milliseconds) between retries.
      • timeout: Maximum time (in milliseconds) to wait for the function to complete.
      • logging: Enable logging for the execution process.
      • context: Additional metadata to pass to the error handler.
  • Returns: A tuple [error, result].

safeExecuteBatch(fns, options?)

Executes multiple functions in parallel and returns an array of [error, result] tuples.

  • Parameters:

    • fns: Array of functions to execute.
    • options: Configuration options for each execution.
  • Returns: An array of [error, result] tuples.

configureSafeExecute(config)

Configures global behavior for safeExecute.

  • Parameters:
    • config: An object with the following properties:
      • errorHandler: A global error handler.
      • defaultValue: A global fallback value.

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

This project is licensed under the MIT License.