1

I am coding using co module on sail framework.

I want to catch InvalidError but error log says 'undefined'.

How can I fix this code?

Co module can't catch ErrorType specification??

detail: function (req, res) {
  co(function *() {
    let errors = [];
    const text = req.param('text');

    if (text.length <= 0) {
      throw new InvalidError('text is required');
    }

  }).catch((InvalidError, err) => {
    sails.log.warn(err);
    errors.push(err.message);
    req.flash('errors', errors);
    res.redirect('/somewhere/view');
  }).catch((Error, err) => {
    sails.log.error(err);
    res.serverError(err);
  });
}

error log is here

warn: undefined
error: undefined
error: Sending empty 500 ("Server Error") response

2 Answers2

1

The catch method only takes a single argument: err. Try:

.catch(err => {
    sails.log.warn(err);
    errors.push(err.message);
    req.flash('errors', errors);
    res.redirect('/somewhere/view');
})
MrWillihog
  • 2,586
  • 19
  • 17
1

You're not useing Bluebird, are you? The standard catch method does not have error type filtering, you'll need to do that yourself:

.catch(err => {
  if (err instanceof InvalidError) {
    sails.log.warn(err);
    errors.push(err.message);
    req.flash('errors', errors);
    res.redirect('/somewhere/view');
  } else if (err instanceof Error) {
    sails.log.error(err);
    res.serverError(err);
  } else {
    console.error("You've thrown a non-error! Shame on you!");
  }
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • thank you for your advise! I am using Bluebird. If using Bluebird, can I choose other option?? – 通りすがりのおっさん Jun 14 '16 at 06:03
  • Well *you* might be using Bluebird, but `co` does not :-) You can either overwrite the global `Promise` variable with Bluebirds implemenation, or you can cast the promise returned by `co(…)` to a Bluebird one like outlined [here](http://stackoverflow.com/a/24315410/1048572) and [there](http://stackoverflow.com/a/30934440/1048572) – Bergi Jun 14 '16 at 06:09