floatleft
floatleft

Reputation: 6541

Response with JSON on request-promise .catch() function

I've found that all my request-promise .catch() methods are using the same logic in my application. So, I would like to write one maintainable function like so:

var handleError = function (error) {
  if (error.statusCode == 401) {
    res.json({
      'message': 'You\'re no longer logged in. Please check your settings and try again.'
    });
  } else {
    res.json({
      'message': 'Something when wrong and it wasn\'t your fault. Please try again.'
    });
  }
};

router.get('/test', function(req, res, next) {
  request({
    uri: 'http://google.com/404'
  }).then(function () {
    console.log('It worked!');
  }).catch(handleError);
});

Although this doesn't work because the handleError() function doesn't have access ExpressJS's response object. How can I return JSON to the page and still maintain everything from one function?

Upvotes: 0

Views: 501

Answers (1)

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

In that case, it's best to write a middleware to handle it.

Alternatively, you can bind res object but again you will have to bind it everywhere to use.

You can learn more about express middleware on its homepage

Also, see express-promise package

Upvotes: 1

Related Questions