shumway
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Shumway Logo Shumway Logo

Surely there must be shumway to make error handling easier!


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).

Package Sidebar

Install

npm i shumway

Weekly Downloads

531

Version

1.0.3

License

MIT

Unpacked Size

43.6 kB

Total Files

64

Last publish

Collaborators

  • pigulla