繁体   English   中英

如何确定变量是否为JavaScript错误?

[英]How do I determine if a variable is an Error in javascript?

我在数组中混合了几个变量,其中一些可能是通用错误或自定义错误(即,由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;

您的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;

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

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

看到这个jsfiddle

Mozilla开发人员网络(MDN)在此处具有有关instanceof运算符的更多详细信息,说明:

instanceof运算符用于测试对象原型链中是否有builder.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM