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



  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.
try..catch diagram workflow

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;
  • 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.
Features steps
We monitor your websites

We monitor your websites

We monitor your websites for crashes and availability. This helps you get an overview of the quality of your applications and to spot trends in your releases.

We notify you

We notify you

We notify you when errors starts happening using Slack, HipChat, mail or other forms of communication to help you react to errors before your users do.

We help you fix bugs

We help you fix bugs

We help you fix bugs quickly by combining error diagnostic information with innovative quick fixes and answers from Stack Overflow and social media.

See how we can help you monitor your website for crashes Monitor your website