Key Points
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. window.onerror
events) to centralize and simplify error handling for easy management and maintenance in different parts of the application. 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. 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:
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(); }
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); });
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; }
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); });
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));
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!