JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 442
  • Score
    100M100P100Q101012F
  • License MIT

Reduce boilerplate code when handling exceptions.

Package Exports

  • shumway
  • shumway/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (shumway) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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.

One approach is to split the error handling and the actual functionality into different functions, e.g. doGetFooFromRemoteSource (which does the remote call but no complex error handling) and getFooFromRemoteSource (which has only error handling).

This module offers a different approach:

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