🎣 catch-decorator
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:
async { try await api // <-- can throw ServerError } catcherr ... }
we can write this:
@ async { await api // <-- 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:
const CatchAll = @CatchAll { throw '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):
@ @ { throw 'ReferenceError here!' ... }
It also works with async methods:
errorMessage = null @ { return }
License:
MIT