0

Suppose I have the following typo in my Node.Js app Javascript code:

    max_weight = Match.floor(max_weight/min_weight)

It's supposed to be Math.floor instead of Match.floor so when the code executes I get the error:

ReferenceError: Match is not defined

and then my Node.Js app quits.

How can I ensure that even if an error like this occurs, the app does not quit but simply reports the error and continues the code execution?

I understand I should solve problems like this before launching into production, but, still, what if I want the code to continue the execution despite the error?

2 Answers 2

2

By wrapping your code in a try catch block, you should be able to

try {
  max_weight = Match.floor(max_weight/min_weight);
}
catch(err) {
  // do something to log error
}

be aware that the lines inside the try block after where the error is found will not be executed.

Sign up to request clarification or add additional context in comments.

Comments

1

This could be achieved in two ways.

First approach is to use node.js global error handling way:

process.on('uncaughtException', function(err) {
  console.log(err); // do something with error or ignore it
});

let max_weight = 17, min_weight = 5;
max_weight = Match.floor(max_weight / min_weight);

Other approach is to handle it locally at code level:

try {
    // trying to do something that might fail should be inside try block
    let max_weight = 17, min_weight = 5;
    max_weight = Match.floor(max_weight/min_weight);
} catch(err) {
    console.log(err); // do something with error or ignore it
}

Clone node-cheat error-handling, run node error-handling.js.

3 Comments

So does it mean that if I use the global handling it won’t quit anymore but will just do the console log ?
One thing you should not do is to listen for the uncaughtException event, emitted read here
Above are possible options specific to what OP has asked, It is not clear yet whether OP is using express or koa or something else, otherwise response could be bit different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.