a Promise extension that provides filtered catch handler
MIT License
Smart Promise is a Promise extension that provides filtered catch handler.
bluebird x 3,541 ops/sec ±1.70% (82 runs sampled)
smart-promise x 99,766 ops/sec ±1.24% (86 runs sampled)
npm install smart-promise
The same native Promise API applies, the only difference is the catch()
method.
Behaves normally as per the native Promise API
A filtered variant of catch
(like other non-JS languages typically have) that lets you only handle specific errors.
The catch handler that is first met that has eligible constructors specified, is the one that will be called.
Extend your existing Promise
Libraries:
const { Smart } = require('smart-promise')
const Promise = Smart(MyPromiseLib)
// or, use the shorthand
const Promise = require('smart-promise')(MyPromiseLib)
Standalone:
const { Promise } = require('smart-promise')
Promise
.then(_ => return a.b.c.d())
.catch(TypeError, error => {
// If the error is a "TypeError", this code block will execute
})
.catch(ReferenceError, error => {
// If the error is a "ReferenceError", this code block will execute instead
})
.catch('TypedErrorName', error => {
// If the error constructor matches "TypedErrorName", this code block will execute instead
})
.catch(error => {
// Generic catch-the rest (error wasn't TypeError nor ReferenceError)
})
You may also add multiple filters for a catch handler:
Promise
.then(_ => return a.b.c.d())
.catch(TypeError, ReferenceError, error => {
// Will end up here on programmer error
})
.catch(NetworkError, TimeoutError, 'SomeError', error => {
// Will end up here on expected everyday network errors
})
.catch(error => {
// Catch any unexpected errors
})
You can also wrap it around existing promises resolvers, this is useful for managing 3rd party generated promises:
const { Promise } = require('smart-promise')
const Library = require('some-other-promise-producting-library')
Promise.resolve(Library.action())
.catch('SomeError', error => {})
If you're using ESlint
or similar tooling, please refer to prefer-promise-reject-errors
Author: Ahmad Nassri • Twitter: @AhmadNassri