Question

I have several variables mixed up in an array and some of them may be generic or custom errors (ie. generated by var v = new Error() or var v = new MyCustomError()).

Is there a generic way to differentiate an instance of Error from any other variable ? Thanks.

Edit: custom errors are in the form :

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

Was it helpful?

Solution 2

You can, for the most part, use the instanceof operator, e.g.

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

See this jsfiddle.

The Mozilla Developer Network (MDN) has more details on the instanceof operator here, stating that:

The instanceof operator tests presence of constructor.prototype in object prototype chain.

Such that, given the following inputs you would get the outputs reflected in the comments:

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

OTHER TIPS

your FacebookApiException doesn't inherit correctly from Error, I suggest doing something like this:

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top