如何确定变量是否是javascript中的错误?

时间:2014-04-30 00:00:30

标签: javascript prototype typeof

我在一个数组中混合了几个变量,其中一些可能是通用或自定义错误(即由var v = new Error()var v = new MyCustomError()生成)。

是否存在将Error实例与任何其他变量区分开来的通用方法?感谢。

修改:自定义错误的格式为:

function FacebookApiException(res) { this.name = "FacebookApiException"; this.message = JSON.stringify(res || {}); this.response = res; } FacebookApiException.prototype = Error.prototype;

2 个答案:

答案 0 :(得分:3)

你的FacebookApiException没有正确地从Error继承,我建议做这样的事情:

function FacebookApiException(res) {
    //re use Error constructor
    Error.call(this,JSON.stringify(res || {}));
    this.name = "FacebookApiException";
    this.response = res;
}
//Faceb... is an Error but Error is not Faceb...
//  so you can't set it's prototype to be equal to Error
FacebookApiException.prototype = Object.create(Error.prototype);
//for completeness, not strictly needed but prototype.constructor
// is there automatically and should point to the right constructor
// re assigning the prototype has it pointing to Error but should be
// FacebookApiException
FacebookApiException.prototype.constructor = FacebookApiException;

答案 1 :(得分:2)

您可以在大多数情况下使用instanceof运算符,例如

var err = new Error();
if (err instanceof Error) {
  alert('That was an error!');
}

请参阅此jsfiddle

Mozilla开发者网络(MDN)提供了有关instanceof运算符here的更多详细信息,并声明:

  

instanceof运算符测试对象原型链中constructor.prototype的存在。

这样,根据以下输入,您将获得在评论中反映的输出:

function C(){} // defining a constructor
function D(){} // defining another constructor

var o = new C();
o instanceof C; // true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false, because D.prototype is nowhere in o's prototype chain
o instanceof Object; // true, because:
C.prototype instanceof Object // true

C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false, because C.prototype is nowhere in o's prototype chain anymore

D.prototype = new C(); // use inheritance
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true