You can use the instanceof
operator (but see caveat below!).
var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false
The above won't work if the error was thrown in a different window/frame/iframe than where the check is happening. In that case, the instanceof Error
check will return false, even for an Error
object. In that case, the easiest approach is duck-typing.
if (myError && myError.stack && myError.message) {
// it's an error, probably
}
However, duck-typing may produce false positives if you have non-error objects that contain stack
and message
properties.