首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >手动/人工抛出带有DOMException的JavaScript

手动/人工抛出带有DOMException的JavaScript
EN

Stack Overflow用户
提问于 2011-02-27 23:09:28
回答 2查看 6.4K关注 0票数 12

是否可以在纯DOMException中手动抛出JavaScript错误?我读过的文件建议构建起来应该相对容易(至少在Java中是这样)。

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

代码语言:javascript
复制
// DOM SYNTAX_ERR (12)
var myDOMException = new DOMException(12,"I'm sorry Dave, I'm afraid I can't do that.");

遗憾的是,这正是我在阅读W3文档之后所期望的,它似乎根本没有指定构造函数。(顺便说一句,虽然我不是IDL的“variant”,但我认为他们的变体将支持构造函数的规范。)

令人沮丧的是,DOMException类潜伏在全球范围内。我该怎么用呢?我能用一下吗?

更新

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

代码语言:javascript
复制
var myDOMException = DOMException.constructor(12,"Error Message");
var myDOMException2 = DOMException.constructor.call(DOMException,DOMException.SYNTAX_ERR,"Error Message");

看来起作用了!

...not太快了。

代码语言:javascript
复制
$> myDOMException instanceof DOMException
false
$> myDOMException2 instanceof DOMException
false

甚至更令人反感的是:

代码语言:javascript
复制
$> myDOMException.constructor
function Number() {
    [native code]
}

一如既往,任何援助都将不胜感激。

更新#2

为了澄清我返回DOMException对象的原因,而不是一个更一般的错误--我正在尝试在纯JavaScript中实现WHATWG的定时文本跟踪规范。在许多情况下,返回DOMException对象需要适当的解决方案,特别是代码为12的实例(SYNTAX_ERR)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-27 23:16:50

至少在火狐中,DOMException不是一个函数。是对象定义了几个常量。

代码语言:javascript
复制
 typeof DOMException === 'object' // true (not 'function')

它可以这样使用:

代码语言:javascript
复制
try {
    throw DOMException;
} catch(e) {
    if (e === DOMException)
        console.log("caught DOMException")
}

如果您试图向DOMException发送信号,但不需要DOMException的实际实例,这是可行的。

丑陋,丑陋的黑客(基本上起作用)

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

代码语言:javascript
复制
function createSyntaxException() {
    try {
        // will cause a DOMException
        document.querySelectorAll("div:foo");
    } catch(e) {
        return e;
    }
}

throw createSyntaxException();

当然,抛出的异常的细节与您的特定情况不匹配,但是结果对象将具有正确的代码并通过instanceof检查。

代码语言:javascript
复制
var e = createSyntaxException();
console.log(e instanceof DOMException); // true
console.log(e.code === e.SYNTAX_ERR); // true

您可以通过子类DOMException和为其(只读)属性添加getter/setter来缓解细节问题。

代码语言:javascript
复制
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";

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

代码语言:javascript
复制
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
票数 12
EN

Stack Overflow用户

发布于 2012-03-24 23:10:08

这是我的裂缝。基于ECMAScript 5和WebIDL的解决方案。我已经与正在开发讨论过这个的W3C/ECMAScript联合任务组一起使用WebIDL。他们说这基本上是不可能的,因为它依赖于内部的平台行为.但这里有些东西可能已经够近了。

代码语言:javascript
复制
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;

}

还有一些测试:

代码语言:javascript
复制
// 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)​
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5136727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档