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

2.0.0 • Public • Published

🎣 catch-decorator

Build Status

Allows you to handle exceptions in class methods with only one annotation (decorator). Idea of errors handling taken from Java.

UPDATE from v2: refactored to use stacked decorators style. Thx @k1r0s for idea :)

Install

npm install catch-decorator

Why?

The main problem of handling errors are using "try/catch" blocks or "catch" methods for Promises. But if we use classes, for example for Vue components, why can't we use method decorators for handling errors?

So, for example, instead of this:

class Messenger {
    async getMessages() {
        try
            await api.getData() // <-- can throw ServerError
        } catch(err) {
            ...
        }   
    }
}

we can write this:

import Catch from 'catch-decorator'
 
class Messenger {
    @Catch(ServerError, handler)
    async getMessages() {
        await api.getData() // <-- can throw custom ServerError
    }
}

much prettier, isn't it?

How to use?

catch-decorator works with any ECMAScript/Typescript classes. If you use Babel, babel-plugin-transform-decorators-legacy is needed. If you use TypeScript, enable --experimentalDecorators flag.

You can handle any thrown error:

import Catch from 'catch-decorator'
 
const CatchAll = Catch(Error, (err: any) => console.log(err.message))
 
class Messenger {
    @CatchAll
    getMessages() {
        throw new TypeError('ReferenceError here!')
        ...
    }
}

or write decorators in stack to handle more than one errors type. In callback as second argument will be passed current instance object (context):

class Messenger {
    @Catch(TypeError, (err, ctx) => {...})
    @Catch(ReferenceError, (err, ctx) => {...})
    getMessages() {
        throw new ReferenceError('ReferenceError here!')
        ...
    }
}

It also works with async methods:

class Messenger {
    errorMessage = null
 
    @Catch(ServerError, (err, ctx) => ctx.errorMessage = err.message)
    getMessages() {
        return fetch(myRequest).then(response => { // can throw ServerError
            ...
        })
    }
}

License:

MIT

Package Sidebar

Install

npm i catch-decorator

Weekly Downloads

4,631

Version

2.0.0

License

MIT

Unpacked Size

18.6 kB

Total Files

28

Last publish

Collaborators

  • batenkovt