由于某些原因,构造函数委托在下面的代码片段中看起来不起作用:
function NotImplementedError() {
Error.apply(this, arguments);
}
NotImplementedError.prototype = new Error();
var nie = new NotImplementedError("some message");
console.log("The message is: '"+nie.message+"'")运行此命令将生成The message is: ''。有什么想法可以解释为什么,或者有没有更好的方法来创建一个新的Error子类?apply到本机Error构造函数有没有我不知道的问题?
发布于 2013-04-28 22:58:05
以不能使用instanceof为代价,下面的代码保留了原始的堆栈跟踪,不使用任何非标准的技巧。
// the function itself
var fixError = function(err, name) {
err.name = name;
return err;
}
// using the function
try {
throw fixError(new Error('custom error message'), 'CustomError');
} catch (e) {
if (e.name == 'CustomError')
console.log('Wee! Custom Error! Msg:', e.message);
else
throw e; // unhandled. let it propagate upwards the call stack
}https://stackoverflow.com/questions/783818
复制相似问题