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

shumway

v1.0.3

Published

Reduce boilerplate code when handling exceptions.

Downloads

3,019

Readme

shumway

Safe and simple to use

Elevator Pitch

Asynchronous calls typically involve some kind of I/O, such as network requests or disk operations, both of which are prone to errors and can fail in all sorts of ways. Oftentimes, especially when in a Clean Architecture, you want to hide implementation details - in this case errors - from the rest of the application.

In order to do so, it is commonly considered good practice to throw more "abstract" errors, so maybe a custom RemoteFooProviderError instead of just letting the error thrown by the used HTTP client bubble up. This is frequently combined with adding some additional logic like so:

class FooProvider {
    public async getFooFromRemoteSource(id: number): Promise<Foo> {
        let response: FooResponse

        try {
            response = await this.httpClient.get(`/foo/${id}`)
        } catch (error) {
            if (error instanceof HttpClientError) {
                if (error.statusCode === 404) {
                    throw new FooNotFoundError(id)
                }

                throw new FooRemoteSourceError(error)
            }

            throw new UnexpectedFooRemoteSourceError(error)
        }

        return new Foo(response.data)
    }
}

While there is nothing wrong with that approach per se, it quickly becomes tedious (and increasingly annoying to maintain) once you have multiple methods that share the same error handling boilerplate. It is also not particularly nice-looking code because the signal-to-noise-ratio is fairly poor.

This is the problem this module sets out to simplify:

class FooProvider {
    @HandleError(
        {
            action: HandlerAction.MAP,
            scope: HttpClientError,
            predicate: error => (error as HTTPError).statusCode === 404,
            callback: (_error, id) => new FooNotFoundError(id),
        },
        {
            action: HandlerAction.MAP,
            scope: HttpClientError,
            callback: error => new FooRemoteSourceError(error),
        },
        {
            action: HandlerAction.MAP,
            callback: error => new UnexpectedFooRemoteSourceError(error),
        },
    )
    public async getFooFromRemoteSource(id: number): Promise<Foo> {
        const response = await this.httpClient.get(`/foo/${id}`)
        return new Foo(response.data)
    }
}

The HandleError decorator is configured with a series of error handlers (the so-called handler chain) which are executed sequentially:

  • first, any 404 responses is mapped to a FooNotFoundError (which is then immediately thrown)
  • if the first handler does not match, any other HttpClientError is mapped to a FooRemoteSourceError (and thrown)
  • and finally, any other error is then mapped to a UnexpectedFooRemoteSourceError

For a more complete (and more realistic) example, check out our use cases, e.g. the API wrapper use case.

Please read the wiki for more detailed information.

Installation

Use your favorite package manager to install, e.g.:

npm install shumway

Basic Usage

Simply decorate your class methods with @HandleError and configure as needed:

class Foo {
    @HandleError({
        action: HandlerAction.RECOVER,
        callback: () => 'my fallback value',
    })
    public async thouShaltNotThrow(): Promise<string> {
        // ...
    }
}

Remember that a handler is only ever called if the wrapped function throws an error.

Please read the wiki for more detailed information.

Caveats and known limitations

  • This library currently works only with asynchronous functions. A version for synchronous functions could be added later if there is a need for it.
  • By its very nature, decorators do not work with plain functions (only class methods).