Home > Web Front-end > JS Tutorial > A Guide to Proper Error Handling in JavaScript

A Guide to Proper Error Handling in JavaScript

Jennifer Aniston
Release: 2025-02-16 13:20:16
Original
198 people have browsed it

A Guide to Proper Error Handling in JavaScript

Key Points

  • Cleverly use the try…catch statement block to effectively manage exceptions, enhancing the debugging process by allowing errors to bubble up to the call stack, thereby displaying errors more clearly.
  • Implement global error handlers (such as window.onerror events) to centralize and simplify error handling for easy management and maintenance in different parts of the application.
  • Use the browser's ability to record detailed error information (including call stack) to improve error diagnosis and have a clearer understanding of the source and context of the error.
  • Fix the asynchronous error handling puzzle by using try…catch in the setTimeout block or using a global error handler suitable for all execution contexts, ensuring that errors in asynchronous code are effectively captured and managed.
  • Enhance error messages by creating custom error types or enriching error messages, making it easier to identify and resolve specific issues and improve the overall robustness of JavaScript code.

Error handling in JavaScript is full of challenges. Follow Murphy's Law, anything that can go wrong will go wrong. This article will explore error handling in JavaScript, cover traps, best practices, and explain asynchronous code and Ajax as examples.

This article was updated on June 8, 2017 to address reader feedback. Specifically, file names have been added to the code snippet, unit tests have been cleaned, wrapper patterns have been added to uglyHandler, and sections about CORS and third-party error handlers have been added.

I think JavaScript's event-driven paradigm adds richness to the language. I like to think of my browser as this event-driven machine, and errors are no exception. When an error occurs, an event will be thrown at a certain moment. In theory, it can be said that errors are just simple events in JavaScript.

If you find this strange, please wear your seat belt as you will have a pretty wonderful journey. In this article, I will only focus on client-side JavaScript.

This topic is based on the concept explained in "Excellent Exception Handling in JavaScript". If you are not familiar with it, I recommend reading the basics. This article also assumes that you have moderate level of JavaScript knowledge. If you want to improve your level, why not sign up for SitePoint Premium and watch our course JavaScript: Next? The first lesson is free.

In either case, my goal is to explore the necessary conditions beyond handling exceptions. After reading this article, the next time you see a good try...catch block, you will think twice before you act.

Demo

The demo program to be used in this article can be found on GitHub, which is presented as follows:

A Guide to Proper Error Handling in JavaScript

All buttons will detonate a "bomb" when clicked. This bomb simulates an exception thrown as a TypeError. The following is the definition of this module:

// scripts/error.js

function error() {
  var foo = {};
  return foo.bar();
}
Copy after login

First, this function declares an empty object named foo. Please note that bar() is not defined anywhere. Let's use a good unit test to verify that this will detonate a bomb:

// tests/scripts/errorTest.js

it('throws a TypeError', function () {
  should.throws(error, TypeError);
});
Copy after login

This unit test uses Mocha for test assertions and uses Should.js for assertions. Mocha is a test runner, and Should.js is the assertion library. If you are not familiar with it, feel free to explore the test API. The test starts with it('description') and ends with a pass/failure in should. Unit tests run on Node and do not require a browser. I recommend you pay attention to these tests, as they prove the key concepts with pure JavaScript.

After cloning the repository and installing the dependencies, you can run the tests using npm t. Alternatively, you can run this single test like this: ./node_modules/mocha/bin/mocha tests/scripts/errorTest.js.

As shown, error() defines an empty object and then tries to access a method. Since bar() does not exist in the object, it throws an exception. Trust me, for dynamic languages ​​like JavaScript, this happens to everyone!

Poor handling

There are some bad error handling next. I've abstracted the handler on the button from the implementation. Here is what the handler looks like:

// scripts/badHandler.js

function badHandler(fn) {
  try {
    return fn();
  } catch (e) { }
  return null;
}
Copy after login

This handler receives a fn callback as a parameter. This callback is then called within the handler function. Unit tests show what it is for:

// tests/scripts/badHandlerTest.js

it('returns a value without errors', function() {
  var fn = function() {
    return 1;
  };

  var result = badHandler(fn);

  result.should.equal(1);
});

it('returns a null with errors', function() {
  var fn = function() {
    throw new Error('random error');
  };

  var result = badHandler(fn);

  should(result).equal(null);
});
Copy after login

As you can see, if something goes wrong, this bad error handler will return null. The callback fn() can point to a legal method or a bomb.

The following click event handler explains the rest of the story:

// scripts/badHandlerDom.js

(function (handler, bomb) {
  var badButton = document.getElementById('bad');

  if (badButton) {
    badButton.addEventListener('click', function () {
      handler(bomb);
      console.log('Imagine, getting promoted for hiding mistakes');
    });
  }
}(badHandler, error));
Copy after login

Oops, I only get one null. This left me ignoring nothing when I tried to figure out what went wrong. This silent failure strategy ranges from bad user experience to data corruption. It's frustrating that I might spend hours debugging the symptoms and ignore the try-catch block. This evil handler will swallow up errors in the code and pretend everything is OK. This may be acceptable for organizations that do not value code quality. However, hiding errors can cause you to spend hours in the future to debug. In a multi-layer solution with a deep call stack, it is impossible to find out where the error is going. As far as error handling is concerned, this is very bad.

Silent failure strategy will make you desire better error handling. JavaScript provides a more elegant way to handle exceptions.

(The following content is similar to the previous output, except that the language and expression have been adjusted subtly to keep the article concise and avoid duplication.)

... (The rest is similar to the previous output, except that the language and expression are adjusted subtly to keep the article concise and avoid duplication.) ...

The above is the detailed content of A Guide to Proper Error Handling in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template