Skip to main content

JS Learning Notes 8_Error Handling

Free2015-04-12#JS#js错误处理

This article introduces JS error handling syntax, error types, error events, and 6 common sense tips for avoiding errors

1. Error Handling Syntax: (JS has no exception concept, all are errors)

try{
  //throw new Error(msg);
  //throw '错误';
  //throw false;
  //throw ...
  //throw operator's operand has no restrictions, can throw anything
}
catch(err){
  //alert(err.message);//message is the only property supported by all browsers
}
finally{
  //
}

Note: [IE7-] has a bug: without catch block, finally block won't execute, so try to use complete try-catch-finally

There's a description error in High-Level Programming (Chinese version page 501):

Readers must remember, as long as code contains finally clause, then regardless of try or catch statement block's return statement will be ignored.

Local test result: For return encountered before entering finally, after finally completes it will still return. Not "ignored" as the book says, should just be ambiguity.

Additionally, JS has same secrets as Java exception handling, for example:

//Code from http://www.cnblogs.com/averey/p/4379646.html
function aaa(){
  var x = 1;

  try {
    return ++x;
  } catch (err) {

  } finally {
    ++x;
  }
  return x;
}

(function(){
  var y = aaa();
  alert(y);//2
})();

For details please check:

Of course, knowing these little secrets is enough, no need to dig deep

2. Seven Error Types

  • Error

  • EvalError

  • RangeError

  • ReferenceError

  • SyntaxError

  • TypeError

  • URIError

3. error Event

As the last line of defense to avoid browser errors, syntax is as follows:

window.onerror = function(msg, url, line){
  return true;//no error
}

Note: Can only use above DOM0 level method to add event handler, because it doesn't follow DOM2 level standard

Note: High-Level Programming Chinese 3rd edition page 506 has some issues, actually returning true means no error, not return false as in the book, test code as follows:

window.onerror = function(e) {
  return true;//Chrome, FF, IE8 all no error
  //return false;//Chrome, FF error, IE8 no error
}
'str'.startWith('x');///trigger error

4. Some Common Sense

  1. Try to use === and !== to compare, to avoid type conversion and type conversion errors

  2. Try to use boolean values in control statements, don't use structures like if(value), because automatically performed type conversion leads to multiple falsy values:

    • false

    • +0/-0

    • undefined

    • null

    • ''/"" (empty string)

    • NaN

These falsy values may lead to unexpected results, if only using === and !== then only false is falsy, can express meaning precisely

  1. Don't use detections like if(value != null) and if(value != undefined), instead should:

    • Use if(value instanceof Type) to detect object values

    • Use if(typeof value === strType) to detect primitive type values

  2. Don't use scripts in body for document.body related DOM operations (add/remove nodes), because may trigger IE errors

  3. External JS files may also cause JS syntax errors, and error messages are often inaccurate, hard to discover, so should do sufficient testing before referencing external scripts

  4. IE has URI length limit not exceeding 2048 characters, therefore when using get instead of post request to optimize performance, should try to reduce query string length (such as using shorter field names)

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment