0

In few words, I have certain NodeJs application running in my company DMZ which basically receives calls from a mobile and forward such calls to other rest services running in another server (WebSphere beyond our DMZ layer).

I have been reading a lot about how NodeJs behaves different from Java (I mean, the default asynchronous NodeJs behavior versus default Java synchronous behavior). As you can imagine, I am bit new to NodeJs logs best practices.

It is very clear for me some rules of thumbs like "don't use try/catch in asynchronous code". Nevertheless, I can't judge what would be the best idea to approach the code bellow neither if I am at least doing an acceptable solution bellow (see the end of my code).

To reveal a bit more about my limitation, I don't know judge properly if such peace of code is asynchronous or synchronous. Well, I guess it is synchronous because I didn't use call back functions neither promises library.

By the way, should I use certain try/catch approach bellow or wrap it in domain? If so, any idea how will be high appreciated.

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

var router = express.Router();

var tokenRoute = router.route('/token');

//bellow one of my NodeJs rest service which basically receives a call from mobile and call forward to certain Spring application to answer back a token
tokenRoute.post(function (req, res) {

  var bilhetagem = {
    cpf: req.body.username,
    servico: 'login'
  };

  logstash.send(bilhetagem);

  var dataAuth = 'grant_type=' + req.body.grant_type +
    '&username=' + req.body.username + '&password=' + req.body.password;

  var auth = req.headers.authorization;

  var args = {
    data: dataAuth,
    headers: { "Content-Type": "application/x-www-form-urlencoded", 'Authorization': auth }
  };

  var backend = ... here it is the rest service from our WebSphere beyond DMZ layer

  client.registerMethod("postMethod", backend, "POST");

  //here relies the main part of doubt. Let's say there is a predictable exception (eg. timeout). What is the best aprroach here?
  client.methods.postMethod(args, function (data, response) {

    res.writeHead(200, { "Content-Type": "application/json" });
    var json = JSON.stringify({
      tokenBackEnd: data
    });
    res.end(json);

  });

});

app.use('/', router);

https.createServer(options, app).listen(config.get('node-porta'));


//here it is my current solution and it does work but I am wondering if I am realy doing a good practice over here.
//PS. I wrote below console.log just to focus on my question but certainly I am logging in file and so on
process.on('uncaughtException', function (err) {
  console.log("process.on(uncaughtException)",err.message);
});
DemeCarvO
  • 487
  • 4
  • 16
  • 28
  • 1
    Does `client.methods.postMethod()` have a means of communicating back an error? That function looks asynchronous to me and I would think it would and could have error handling in it. – jfriend00 Apr 05 '17 at 22:57
  • 1
    For discerning whether something is asynchronous, you either read the documentation or you determine from the way it is called. See [Node.js: How to programmatically determine asynchronous?](http://stackoverflow.com/questions/29000772/node-js-how-to-programmatically-determine-asynchronous/29000806#29000806). – jfriend00 Apr 05 '17 at 22:59
  • 2
    FYI, there's nothing wrong with using try/catch around synchronous code (if you think there's any chance it can throw). – jfriend00 Apr 05 '17 at 23:00
  • @jfriend00, thanks. I understood that there is some risks involved in using try/catch around asynchronous (PS. let me put in spot light "a"sync.). You can read "try-catch will not behave as you might expect it to in asynchronous situations" in https://www.toptal.com/nodejs/top-10-common-nodejs-developer-mistakes or "Another thing to be careful about with try...catch is the risk of wrapping your completion callback inside the try statement " in http://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling. – DemeCarvO Apr 06 '17 at 14:44
  • I read "If a function is asynchronous it does not directly return the result from the function call". I understand that "client.methods.postMethod(args, function (data, response){... res.send}" is asynchronous. Assuming I am right when I said this is asynchronous and based on previous comment about risks related to try/catch + asynchronous code, what is the best or, at a least, acceptable way to deal with errors here? Would be use domains to call "client.methods.postMethod" or the way I have already done at the end of my code at least acceptable (eg. process.on('uncaughtException'...)? – DemeCarvO Apr 06 '17 at 15:06
  • 1
    That method needs a way to pass the error to the callback function and the callback would send a different response if there was an error such as `res.status(500).json({error: "some error"});`. – jfriend00 Apr 06 '17 at 15:10
  • @jfriend00, thanks. Can you give me an example? – DemeCarvO Apr 07 '17 at 14:59
  • 1
    This concept of providing an error parameter to a callback is core to nodejs asynchronous coding: http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/. All nodejs asynchronous operations follow this same scheme. – jfriend00 Apr 07 '17 at 15:32

0 Answers0