04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 14: Error Handling and Debugging<br />

❑<br />

There ’ s less of a chance that an error will occur in the process of logging the error. Most Ajax<br />

communication is handled through functionality wrappers provided by JavaScript libraries. If<br />

that library ’ s code fails, and you ’ re trying to use it to log the error, the message may never get<br />

logged.<br />

Whenever a try - catch statement is used, it ’ s likely that the error should be logged. Here is an example:<br />

for (var i=0, len=mods.length; i < len; i++){<br />

try {<br />

mods[i].init();<br />

} catch (ex){<br />

logError(“nonfatal”, “Module init failed: “ + ex.message);<br />

}<br />

}<br />

In this code, logError() is called when a module fails to initialize. The first argument is “ nonfatal ” ,<br />

indicating the severity of the error, and the message provides contextual information plus the true<br />

JavaScript error message. Error messages that are logged to the server should provide as much<br />

contextual information as possible to help identify the exact cause of the error.<br />

Debugging Techniques<br />

Before JavaScript debuggers were readily available, developers had to use creative methods to debug<br />

their code. This led to the placement of code specifically designed to output debugging information in one<br />

or more ways. The most common debugging technique was to insert alerts throughout the code<br />

in question, which was both tedious, because it required cleanup after the code was debugged, as well as<br />

annoying if an alert was mistakenly left in code that was used in a production environment. Alerts are no<br />

longer recommended for debugging purposes, because several other, more elegant solutions are available.<br />

Logging Messages to a Console<br />

IE 8, Firefox, Opera, Chrome, and Safari all have JavaScript consoles that can be used to view JavaScript<br />

errors. All three also allow you to write directly to the console from code. For this to work in Firefox,<br />

you ’ ll need to have Firebug installed ( www.getfirebug.com ), since it ’ s the Firebug console that is used<br />

in Firefox. IE 8, Firefox, Chrome, and Safari allow you to write to the JavaScript console via the console<br />

object, which has the following methods:<br />

❑<br />

❑<br />

❑<br />

❑<br />

error( message ) — Logs an error message to the console<br />

info( message ) — Logs an informational message to the console<br />

log( message ) — Logs a general message to the console<br />

warn( message ) — Logs a warning message to the console<br />

488

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!