Error Handling in JavaScript

Tagged:  

This article from Clientside discusses three types of error handling in JavaScript:

  • Graceful: if possible, just ignore the error and continue with some default state or without a meaningful value
  • Debug: throw a warning to the dbug.log method but continue otherwise
  • Break: Either explicitly throw an error or (more often) just let the error that is thrown at runtime be thrown

Graceful Examples
Graceful degradation includes some default behavior that occurs when data is missing or an expected result does not occur.

this.id = this.options.id || 'StickyWin_'+new Date().getTime();

A common practice of graceful error handling is to include Try/Catch statements

getContent: function(){
    try {
        new Ajax((this.options.ajaxLink || this.options.observer.href), $merge(this.options.ajaxOptions, {
                onComplete: this.show.bind(this)
            })
        ).request();
    } catch(e) {
        dbug.log('ajax error on PopupDetail: %s', e);
    }
}

Debug Example - warning the user

var ln = this.options.ajaxLinks.length;
if(ln <= 0) ln = this.options.details.length;
if (this.options.observers.length != ln)
    dbug.log("warning: observers and details are out of sync.");

Break Example - toss that exception

ret = Date.$months[month - 1] || false;
if (!ret) throw new Error('Invalid month index value must be between 1 and 12:' + index);

Read the full post over at Clientside

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <div> <blockquote> <object> <embed> <img> <param>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Copy the characters (respecting upper/lower case) from the image.