0.0.2 • Published 9 years ago

catchmap v0.0.2

Weekly downloads
4
License
MIT
Repository
github
Last release
9 years ago

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

9 years ago

0.0.1

9 years ago