使用JavaScript手动/人工抛出DOMException

时间:2011-02-27 23:09:28

标签: javascript dom

是否可以在纯JavaScript中手动抛出DOMException错误? Documentation I've read表明它应该相对容易构建(至少在Java中。)

但是,在Chrome中,以下代码返回TypeError: Illegal constructor

// DOM SYNTAX_ERR (12)
var myDOMException = new DOMException(12,"I'm sorry Dave, I'm afraid I can't do that.");

令人遗憾的是,这是我在阅读the W3 docs之后所期望的,它似乎根本没有指定构造函数。 (顺便说一句,虽然我并不特别对IDL'非常',但我认为他们的变体会支持构造函数的规范。)

令人沮丧的是,DOMException类潜伏在全局范围内。我怎么用呢? 可以我用它吗?

更新

自从我写这篇文章以来,我做了几个发现 - 即:

var myDOMException = DOMException.constructor(12,"Error Message");
var myDOMException2 = DOMException.constructor.call(DOMException,DOMException.SYNTAX_ERR,"Error Message");

看起来很有效!

......没那么快。

$> myDOMException instanceof DOMException
false
$> myDOMException2 instanceof DOMException
false

甚至可能更多的输出:

$> myDOMException.constructor
function Number() {
    [native code]
}

与往常一样,我们将非常感谢任何协助。

更新#2

只是为了澄清我返回DOMException对象的原因而不是更通用的错误 - 我试图在纯JavaScript中实现WHATWG's Timed Text Track spec。有许多实例需要一个正确的解决方案来返回一个DOMException对象,特别是一个代码为12的对象(SYNTAX_ERR。)

2 个答案:

答案 0 :(得分:7)

至少在Firefox中,DOMException不是一个功能。 an object定义了几个常量。

 typeof DOMException === 'object' // true (not 'function')

可以像这样使用:

try {
    throw DOMException;
} catch(e) {
    if (e === DOMException)
        console.log("caught DOMException")
}

如果您尝试发信号DOMException但不需要DOMException的实际实例,则此方法有效。

丑陋,丑陋的黑客(基本上可行)

如果您绝对需要具有DOMException代码的SYNTAX_ERR实例,则可以执行导致创建一个代码的操作,并throw执行以下操作:

function createSyntaxException() {
    try {
        // will cause a DOMException
        document.querySelectorAll("div:foo");
    } catch(e) {
        return e;
    }
}

throw createSyntaxException();

抛出的异常的细节当然不符合您的具体情况,但生成的对象将具有正确的代码并通过instanceof检查。

var e = createSyntaxException();
console.log(e instanceof DOMException); // true
console.log(e.code === e.SYNTAX_ERR); // true

您可以通过继承DOMException并为其每个(只读)属性添加getters / setter来缓解详细信息问题。

function DOMExceptionCustom() {
    var message;
    this.__defineGetter__("message", function(){
        return message;
    });
    this.__defineSetter__("message", function(val){
        message = val;
    });
}

// subclass DOMException
DOMExceptionCustom.prototype = createSyntaxException();

var err = new DOMExceptionCustom();
err.message = "my custom message";

生成的对象具有所需的属性:

console.log(err.code === err.SYNTAX_ERR); // true
console.log(err.message); // "my custom message"
console.log(err instanceof DOMExceptionCustom); // true
console.log(err instanceof DOMException); // true

答案 1 :(得分:1)

这是我对它的抨击。基于ECMAScript 5和WebIDL的解决方案。 我正在使用正在使用WebIDL的W3C / ECMAScript联接任务组discussed this。他们说基本上不可能这样做,因为它依赖于内部平台行为......但这里的内容可能足够接近。

function CustomDOMException(code, message) {
    //throw on missing code
    if (typeof code !== "number") {
        throw TypeError("Wrong argument");
    }

    //we need the codes, to get the "name" property.  
    var consts = {
        1: "INDEX_SIZE_ERR",
        3: "HIERARCHY_REQUEST_ERR",
        4: "WRONG_DOCUMENT_ERR",
        5: "INVALID_CHARACTER_ERR",
        7: "NO_MODIFICATION_ALLOWED_ERR",
        8: "NOT_FOUND_ERR",
        9: "NOT_SUPPORTED_ERR",
        11: "INVALID_STATE_ERR",
        12: "SYNTAX_ERR",
        13: "INVALID_MODIFICATION_ERR",
        14: "NAMESPACE_ERR",
        15: "INVALID_ACCESS_ERR",
        17: "TYPE_MISMATCH_ERR",
        18: "SECURITY_ERR",
        19: "NETWORK_ERR",
        20: "ABORT_ERR",
        21: "URL_MISMATCH_ERR",
        22: "QUOTA_EXCEEDED_ERR",
        23: "TIMEOUT_ERR",
        24: "INVALID_NODE_TYPE_ERR",
        25: "DATA_CLONE_ERR"
    }
    if ((code in consts) === false) {
        throw TypeError("Unknown exception code: " + code);
    }

    //props for adding properties
    var props = {};
    //generate an exception object 
    var newException;
    try {
        //force an exception to be generated; 
        document.removeChild({})
    } catch (e) {
        //use it as the prototype  
        newException = Object.create(Object.getPrototypeOf(e));
    }
    //get the name of the exception type        
    var name = consts[code];

    //add the properties
    var props = {value: null, writable: true, enumerable: false, Configurable: true};
    //name
    props.value = name; 
    Object.defineProperty(newException, "name",    props);
    props.value = code; 
    Object.defineProperty(newException, "code",    props);
    props.value = message; 
    Object.defineProperty(newException, "message", props);

    //Make sure it "stringifies" properly 
    var finalMessage;
    var obj = this;
    if (typeof message === "function") {
        finalMessage = function() {
            return message.call(newException)
        }
    } else {
        finalMessage = function() {
            return name + ": DOM Exception " + code;
        }
    }
    props.value = function() {
        return finalMessage.call(newException)
    }

    Object.defineProperty(newException, "toString", props);
    return newException;

}

还有一些测试:

// Throws SYNTAX_ERR    
console.log(new CustomDOMException(12)); 

// Custom message 
console.log(new CustomDOMException(1, "ERROR!")); 

// Custom message 
console.log(new CustomDOMException(1, function() {
    return "Custom Err:" + this.name + " : " + Date.now()
}));

// Throws TypeError     
try {
    new CustomDOMException(2)
} catch (e) {
    console.log(e);    
}

// Throws TypeError
try {
    new CustomDOMException()
} catch (e) {
    console.log(e);    
}    

// Throws TypeError    
try {
    new CustomDOMException("Wee!")
} catch (e) {
    console.log(e);    
}

//Check the inheritance chain     
var ext = new CustomDOMException(17);
var isInstance = ext instanceof DOMException;
console.log("instanceof DOMException: " + isInstance)​