catchmap

0.0.2 • Public • Published

npm travis npm

catchmap

Utility for removing tedious error checking.

Works great with promises and blends nicely with co and koa.

In short, catchmap(...errors) creates a function (err) {} that will devour matching errors and re-throw the rest.

Example

catchmap(...) takes care of checking error types and Error.code for you.

// Clear and readable
readFile()
  .then(JSON.parse)
  .catch(catchmap('ENOENT',SyntaxError))
  .then(function (){
    // do some business
  })
  ...
// Yawn, do I have to read all this error checking?
readFile()
  .then(JSON.parse)
  .catch(function (err){
    // This code is hard on the eyes
    if (err.code === 'ENOENT'){
      return
    }
    if (err instanceof SyntaxError){
      return
    }
    throw err
  })
  .then(function (){
    // do some business
  })
  ...
 

Errors can also be mapped to values using catchmap(...).to(value).

somePromise()
  .catch(catchmap(Error).to(123))
  .then(function (v){
    // if Error was thrown, then v === 123
  })
 

Optimize it a bit by sharing instances of catchmap.

 
var allowAcceptableError = catchmap('ENOENT', SyntaxError)
// allowAcceptableError is equivalent with
// catchmap('ENOENT',SyntaxError).to(undefined)
 
somePromise()
  .catch(allowAcceptableError)
  .then(function (){
    // do some business
  })
  ...

Package Sidebar

Install

npm i catchmap

Weekly Downloads

2

Version

0.0.2

License

MIT

Last publish

Collaborators

  • jlarsson