How do I process a JSON in the event of a request-Promise failure?

Asked

Viewed 457 times

2

I have 2 Microservices, one in Nodejs and the other in Spring. Nodejs contains the domain of events (parties, birthdays etc) and Java the domain of users.

When viewing Nodejs event endpoints, I also consult users endpoints and aggregate the equivalent results in a single response - abstracting the second API.

The idea is that the microservice in Nodejs works independently of the microservice written in Java. My problem is in implementing the code in Nodejs, to address the case where the second microservice (Java) is unavailable.

var request = require('request-promise');
const Evento = require('./evento')
const url_api_externa = "http://localhost:8080/usuarios/"

Evento.methods(['get', 'post', 'put', 'delete'])
Evento.updateOptions({ new: true, runValidators: true })

Evento.after('get', function (req, res, next) {
  var eventos = res.locals.bundle
  var url = url_api_externa
  var path = req.path

  path = path.replace('/eventos', '')
  path = path.replace('/', '')

  if (path != '') {
    url = url + res.locals.bundle.idCriador
  }

  consultaExterna(url).then(function (body) {
    res.json({ eventos, criadores: body })
  }
    , function (err) {
      console.error("Falha ao trazer dados do microserviço:" + err);
      next()
    });
});

Evento.before('post', function (req, res, next) { hasUsuario(req, res, next); });
Evento.before('put', function (req, res, next) { hasUsuario(req, res, next); });

function hasUsuario(req, res, next) {
  var url = url_api_externa + req.body.idCriador

  //Só prossegue com a requisição/ação se o idCriador for equivalente a um usuário existente na API externa
  consultaExterna(url).then(function (body) {
    next();
  }, function (error, res) {

    var erroAPIExterna = {
      mensagemDesenvolvedor: "Microserviço externo indisponível",
      status: 404,
      titulo: "O módulo de usuários não está disponível no momento, tente mais tarde"
    }

    if (res != null) {
      erroAPIExterna = error.error
    }

    console.error("Erro:" + error);
    res.status(erroAPIExterna.status).json({ erro: erroAPIExterna.titulo });
  });
}

function consultaExterna(url) {
  return request({
    'method': 'GET',
    'uri': url,
    'json': true,
    'headers': {
      'User-Agent': 'MicroserviceNodeJS'
    }
  });
}

module.exports = Evento

In the line 51 i display the java api error messages in the nodejs api - if it occurs. However, when the java service is unavailable I should be able to send the default unavailability message to my Nodejs api and that’s where my problem starts because they are in a file that failed, so my answer is null and my error is non-null (econrefused bláblá).

What I would need to do is send the requisition that is one level above (that of Nodejs) and not this one that failed, triggering the error as a response. Something similar to next(). json({error}), where next() is my Nodejs request that is being processed and should deliver my message.

Any guesses on how to solve/implement this?

  • You want to pass the object with the error (if it occurs) to the next middleware function?

  • Exactly @ruanmartinelli!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.