代码改变世界

JavaScript Patterns 3.8 Error Objects

2014-06-05 23:56  小郝(Kaibo Hao)  阅读(337)  评论(0编辑  收藏  举报

The error objects created by constructors(Error(),  SyntaxError(), TypeError(), and others) have the following properties:

name

The name property of the constructor function that created the object; it could be the general “Error” or a more specialized constructor such as “RangeError”.

message

The string passed to the constructor when creating the object.

You can be creative when it comes to your custom error objects and use them to restore the application state back to normal.

try {

    // something bad happened, throw an error

    throw {

        name: "MyErrorType", // custom error type

        message: "oops",

        extra: "This was rather embarrassing",

        remedy: genericErrorHandler // who should handle it

    };

} catch (e) {

    // inform the user

    alert(e.message); // "oops"

    // gracefully handle the error

    e.remedy(); // calls genericErrorHandler()

}