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 🙏

© 2024 – Pkg Stats / Ryan Hefner

callguard

v2.0.0

Published

Callback exception guard

Downloads

204,086

Readme

npm version downloads build status coverage status

Your callback exception guard

Rationale

When using API's with callback support, the 3rd party module will call your function. Most of Node.js' asynchronous functions work like this. If you unintentionally throw an exception there, you won't know what happens - what is that module supposed to do?

Promises are a solution to this, as they propagate the error back to you transparently through the promise chain, but arbitrary callbacks lack this defined flow.

There are other situations where callbacks are used, and where promises won't automatically solve the handling of exceptions.

To ensure you don't throw back in a callback, guard your callback function with either syncGuard or asyncGuard.

Usage

Import

import { syncGuard, asyncGuard } from 'callguard'
// or
const { syncGuard, asyncGuard } = require( 'callguard' );

API

callguard exports two functions, syncGuard and asyncGuard. The former guards against synchronous exceptions (but can catch asynchronous too), while the latter guard against both.

For callbacks that either expect no particular return value, or a synchronous value, use syncGuard (optionally enable catchAsync), and for callbacks that are allowed (and expected) to returned synchronously or asynchronously (through promises), use asyncGuard.

Create the guards using these functions and provide an error handler (and optionally options).

const sGuard = syncGuard( errorHandler[, options ] ); // synchronous guard
const aGuard = asyncGuard( errorHandler[, options ] ); // asynchronous guard

The returned values are function wrappers that takes a function as input, and returns a new one as output. The returned functions are safe in that they will not throw. Asynchronously guarded functions will not returned rejected promises either. The guards can be re-used as many times as necessary, both the wrapped functions, as well as the wrapper generators (sGuard and aGuard in this example). They are all stateless.

fs.open( 'file', 'r', sGuard( myCallback ) );
// and for asynchronous calls:
translateThing( thing, aGuard( myAsyncTranslator ) );

By default, the value returned from guarded functions when an error was detected, is null. This can be altered using the defaultReturn option.

When debugging an unwanted exception (caught by these guards), it may be hard to know where it came from. To get longer stack traces from the guards construction, usage and call, enable longStackTraces. This has a severe performance impact (even in success-flow where no exceptions are thrown!), so you probably only want this when debugging.

These are the function signatures and the default options:

syncGuard(
    errorHandler,
    {
        defaultReturn: null,
        longStackTraces: false,
        catchAsync: false,
    }
);

asyncGuard(
    errorHandler,
    {
        defaultReturn: null,
        longStackTraces: false,
    }
);

Example

Consider the following unsafe code. What if doSomethingWithFd throws? Maybe this logic is within another module we don't have control over...

fs.open( 'my-file', 'r', ( err, fd ) =>
{
    // We REALLY don't want to throw here
    doSomethingWithFd( fd ); // Please don't throw!
});

Turn it into:

// Create a synchronous guard, forward exceptions to console.error.
// This is just an example, you might want other logic.
const guard = syncGuard( console.error.bind( console ) );

fs.open( 'my-file', 'r', guard( ( err, fd ) =>
{
    // We really shouldn't throw here, it is not logically sound
    doSomethingWithFd( fd ); // But it's guarded anyway, so we're safe
} ) );

Now, if doSomethingWithFd would throw, this wouldn't propagate to the fs.open function, but instead be printed to the console.

Promisification

One typical example is when using promises in a codebase, but needing to react to callbacks. In this case, it would often be a bug to throw in the callback, and if this is wrapped in a new Promise( ) function body, the promise can easily be canceled while the callback remains exception safe.

NOTE; It will probably be expected that the promise can be rejected, but only because otherLib fails/throws, not that the logic here throws (that's a handling error). callguard will not fix such bugs in your code, but it will ensure you can safely handle it in the promise chain.

const p = new Promise( ( resolve, reject ) =>
{
    // Map mistakes in throwing back at <otherLib> to this promise rejection
    const guard = syncGuard( reject );

    otherLib.on( 'data', guard( data =>
    {
        // We can handle data here, and if we throw, it will reject <p>
        doStuffWithData( data ); // This is safe
    } ) );

    otherLib.on( 'end', guard( ( ) =>
    {
        // Also safe callback, also guarded.
        // If assembleData throws, the promise will be rejected.
        resolve( assembleData( ) ); // This is safe
    } ) );

    otherLib.on( 'error', reject ); // Not everything must be guarded
} );