Friday, February 14, 2025

JavaScript Error Handling: Why You Need it

While error handling is not new to JavaScript, it seems that a lot of people aren’t quite sure how to handle errors in the most productive way. Actually, it’s an issue that affects most programmers. We like our code to work well, so we tend to run it in such a way that maximizes its chances of success.

One of the side effects of this tendency is that bugs are only dealt with after everything works. This can lead to a lot of haphazard error handling that is both hard to debug and less than useful to us. The purpose of this article is to outline some of the major reasons why you need to consider error handling sooner rather than later in a Web application’s development cycle.

How I Learned the Hard Way about the Importance of Error handling

The reasoning behind the subject of this article is that you can’t structure your error handling code in a useful way until you understand the reasons behind it. Funny enough, I myself never gave it a whole lot of thought until the last few years. Previously, I always made sure to include error handling, but I never had a clear purpose of what it was I was trying to accomplish with it. The change came when I had to support an ASP Web application that utilized an especially flaky third-party DLL component. It was always crashing and throwing up obtuse error messages that were really no help whatsoever! That meant that every time we got a call, we had to spend hours getting to the bottom of the problem.

Gradually, I began to place exception handling in various places in the code and included clear messages for typical errors. Seeing understandable messages made the users feel a lot better, even though the application crashed just as much as before. The difference was that they knew right away what went wrong, so their attitude went from one of panic to “oh that again.” They also had confidence that since the error was known, we would be able to get the application back up and running quickly.

The moral of the story is this: structuring your error handling in such a way that instills confidence in the users is paramount! The flip side is that you should avoid having the application crash at all costs. It makes it look like it’s badly designed and that it’s doing things that it shouldn’t be. In actual fact, many errors are expected and part of the regular work process. For instance, there is a dreaded bug in Java called the NullPointerException that occurs whenever you attempt to access a member whose object has not yet been instantiated. JavaScript has the same issue, only it’s called the “undefined” error:

function doSomething( anObject ) {

//this line will fail because anObject is undefined!
//displays: "'undefined' is null or not an object" error.
var aProperty = anObject.getProperty();
}
var myObject;
doSomething(myObject);

Putting a Plan In Place

You should have a plan in place for making sure that all object calls are dealing with an instantiated (or static) object. In one Java project I worked on, we decided to never return uninstantiated objects. Instead, we would initialize every object to an empty one using the default constructor. In JavaScript, creating an empty object is exactly the same, except that you can use the or (||) operator to detect an undefined object:

  var anObject = GetMyObject() || new MyObject();

Getting an undefined object back is sometimes indicative of a serious problem. In that event, better to nip things in the bud. What you’ll need here is a sure fire way to ascertain the state of your object. Many people use the typeof() operator/function – as in if(typeof(x)==’undefined’) – because it never throws an error. However, it’s overkill in this usage, as you can compare the object directly to the undefined object using the strict equal operator (===), or in our case, using the strict not equal operator (!==).

What I like to do with the information gleaned from the strict comparison test is set a boolean. That way you can always check whether or not a function succeeded without having to resort to error handling. Better to leave that for truly unexpected occurrences:

function doSomething( anObject ) {

  var aProperty;
  
  if ( anObject !== undefined ) { 
	  aProperty = anObject.getProperty();
  } else {
		return false;
	}
	
	return true;
}
var myObject;
//more code….
if (!doSomething(myObject)) {
  //handle error
	return;
}

Get The Details!

Another important reason to include proper error handling in your Web applications is to help you fix it for the next release. Once you’ve released an application into production, you’ll no doubt see the same kinds of issues coming up on a regular basis. Depending on the severity, you may want to fix them for the next release. And for that, you need details, lots of ’em! JavaScript errors are notorious for being cryptic and difficult to pin down. Therefore, the more detailed your own error handling is, the easier it will be for you to track down an error’s cause.

It’s not just a matter of saving yourself and the users grief. Application errors are the main gateway for hackers and thieves. That’s how they typically find vulnerabilities into a system. Just like a browser’s code can have security holes in it, so too can your scripting code! Don’t be over confident in the scripting sand box protecting your data. If a bug in your code allows someone to gain access to an underlying component, they may be able to cause massive harm to your infrastructure, data, and company’s reputation. The use of Ajax has only increased Web developers’ responsibility. According to Pete Lindstrom, Director of Security Strategies with the Hurwitz Group:

Web applications are the most vulnerable elements of an organization’s IT infrastructure today. An increasing number of organizations (both for-profit and not-for-profit) depend on Internet-based applications that leverage the power of AJAX. As this group of technologies becomes more complex…, and, if organizations do not secure their web applications, then security risks will only increase.

Some of the most important error details to include are:

  • A unique error number or code. I prefer to use codes for my own errors, because it’s a lot more meaningful than a number, and you can still use it to test for the occurrence of that particular error.
  • The file name and path.
  • The line number and/or function name.
  • The Error Type, i.e., conversion error, array indexOutOfBounds, validation, etc…
  • A simple description for the user.
  • A more detailed description for the system administrator. This could include a stack trace or flush of an object’s data.

Conclusion

There are many compelling reasons why error handling must be an integral part of your application development. In the next installment of this series, we’ll be taking a look at how to code your exception handling in JavaScript. Topics will include the use of try/catch/finally blocks, throwing exceptions, and creating your own customs ones.

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured