From our very own Rob Rothermel, this is definitely the way to go when it comes to error catching.
try {// potentially error causing code} catch (e) {}So… this is what some of you have seen before. We can do all kinds of fun things with this from here though… The variable ‘e’ that is passed into the catch is an Error object that has all kinds of information about what went wrong. As with Java, we can do custom error handling based on what actually went bad.The code above only eats the error and it disappears. Generally… this is awesome for code we deploy… the end-user never sees an error. However… try…catch blocks eat every error. So troubleshooting around these blocks can get miserable. In Java, the most basic try…catch block you’ll ever see always includes a e.printStackTrace() to show the error. Since the release of the Firebug console… we can now do the same, but better
try {// code} catch (e) {if (window.console) // check to make sure we have a consoleconsole.log(e);}Now the error only appears if you check the Firebug console. No warnings or errors appear for end users, but we can immediately see what went wrong.We can actually take this one step further… if we want to throw our own custom errors.try {var obj = document.getElementById(’someDiv’);if (!obj)throw new Error(”someDiv wasn’t found”);if (!/required text/i.test(obj.innerHTML))throw new Error(”someDiv doesn’t contain the required text”);} catch (e) {if (window.console) console.log(e);
Posted by Chris Martin on Sep 11, 2008
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.