JavaScript Error Handling

JavaScript error handling can be helpful to help debug code. Although we think we are good enough at programming sometimes we still face errors. These errors can occur due to inattention, not necessarily due to lack of knowledge, because of an erroneous server response or many other reasons for which we lose a lot of time to figure out what's the cause.

Commonly, a script immediately stops in case of an error occurred, printing it into the console.

We are lucky that there is a syntax construct try..catch that represent the handling of exceptions due to data or coding errors during program execution.

Try..Catch syntax
The try..catch construct has two main blocks: try, and then catch.

try {

  // Code to test

} catch (err) {

  // Error handling
  
  // If there was an error they are put into an object
  // In the case above: 'err' is an object that has multiple
  // properties we can pull values off and use.
  
  // Note - error messages will vary depending on browser

}

Workflow:

  1. First, the code from try block is executed.
  2. If there were no errors, then catch(err) block is ignored (the execution reaches the end of try and then jumps over catch).
  3. If an error occurs, then try block execution is stopped, and the control flows to the beginning of catch(err). The err variable (can be named anything) contains an error object with details about what’s happened.

So, if an error occurs inside the try block, the script will not halt, and we have a chance to handle it in catch block.

Error object
When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to catch:

try {
  // ...
} catch(err) { // <-- the "error object", could use another word instead of 'err'
  // ...
}

The error object inside catch block has the following properties:

  • err.error: the result of the error;
  • err.name: type of error (EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError);
  • err.message: provides explanation of message;
  • err.stack: stack trace of error;
  • err.filename: the name of the file where the error is in;
  • err.linenumber: the line where the error occurs on.