使用JavaScript手动/人工抛出DOMException

Chr*_*her 10 javascript dom

是否可以在纯JavaScript中手动抛出DOMException错误?我读过的文档表明它应该相对容易构建(至少在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.");
Run Code Online (Sandbox Code Playgroud)

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

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

更新

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

var myDOMException = DOMException.constructor(12,"Error Message");
var myDOMException2 = DOMException.constructor.call(DOMException,DOMException.SYNTAX_ERR,"Error Message");
Run Code Online (Sandbox Code Playgroud)

看起来很有效!

......没那么快

$> myDOMException instanceof DOMException
false
$> myDOMException2 instanceof DOMException
false
Run Code Online (Sandbox Code Playgroud)

甚至可能更多的输出:

$> myDOMException.constructor
function Number() {
    [native code]
}
Run Code Online (Sandbox Code Playgroud)

与往常一样,任何援助将不胜感激.

更新#2

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

Way*_*ett 8

至少在Firefox中,DOMException不是一个功能.它是一个定义几个常量的对象.

 typeof DOMException === 'object' // true (not 'function')
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用:

try {
    throw DOMException;
} catch(e) {
    if (e === DOMException)
        console.log("caught DOMException")
}
Run Code Online (Sandbox Code Playgroud)

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

丑陋,丑陋的黑客(基本上有效)

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

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

throw createSyntaxException();
Run Code Online (Sandbox Code Playgroud)

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

var e = createSyntaxException();
console.log(e instanceof DOMException); // true
console.log(e.code === e.SYNTAX_ERR); // true
Run Code Online (Sandbox Code Playgroud)

您可以通过DOMException为每个(只读)属性创建子类并添加getter/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";
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)