在JS中,似乎不可能检查传递给函数的参数是否实际为'error'类型或error实例。

例如,这是无效的:

Typeof err === 'error'

因为只有6种可能的类型(以字符串的形式):

typeof操作符以字符串形式返回类型信息。typeof返回六种可能的值:

“数字”,“字符串”,“布尔”,“对象”,“函数”和“未定义”。

MSDN

但如果我有一个简单的用例,像这样:

function errorHandler(err) {

    if (typeof err === 'error') {
        throw err;
    }
    else {
        console.error('Unexpectedly, no error was passed to error handler. But here is the message:',err);
    }
}

那么,确定参数是否为Error实例的最佳方法是什么呢?

instanceof操作符有什么帮助吗?


当前回答

只需使用error.name

函数_err(type = false) { 如果(类型){ 抛出新的TypeError('哦,糟糕!') } 抛出新的错误('哦,糟糕!') } 尝试{ _err(真正的) } catch(错误){ console.log(typeof error.name, error.name, error.name === 'TypeError') } 尝试{ _err () } catch(错误){ console.log(typeof Error .name, Error .name, Error .name === 'Error') }

其他回答

对于那些正在寻找某种“官方”方式的人(就像我一样),这是MDN推荐的:

try {
  myRoutine();
} catch (e) {
  if (e instanceof RangeError) {
    // statements to handle this very common expected error
  } else {
    throw e;  // re-throw the error unchanged
  }
}

只需使用error.name

函数_err(type = false) { 如果(类型){ 抛出新的TypeError('哦,糟糕!') } 抛出新的错误('哦,糟糕!') } 尝试{ _err(真正的) } catch(错误){ console.log(typeof error.name, error.name, error.name === 'TypeError') } 尝试{ _err () } catch(错误){ console.log(typeof Error .name, Error .name, Error .name === 'Error') }

你可以进一步从@iota得到答案,并通过getPrototypeOf()或已弃用的__proto__属性检查测试对象的内部[[Prototype]]属性。

如果对象是一个错误,它继承自error .prototype。也许是这样的:

// the object you want to check 
const objectToCheck = new Error();

// current way
console.log(Object.getPrototypeOf(objectToCheck) === Error.prototype);  /* true*/

// deprecated way
console.log(objectToCheck.__proto__ === Error.prototype);  /* true */

打印稿的解决方案

可以定义用户定义的类型保护,只需要定义一个返回类型为类型谓词的函数

你可以像这样检查一个变量是否有错误

const isError = (err: unknown): err is Error => err instanceof Error;

然后在try catch中像这样验证它

try {
  login(username, password);
} catch (err) {
  if (isError(err)) {
  console.log(err.message);
}

感谢@Trott的代码,我只是使用了相同的代码,并添加了一个实时工作的示例,以造福他人。

<html> <body > <p>The **instanceof** operator returns true if the specified object is an instance of the specified object.</p> <script> var myError = new Error("TypeError: Cannot set property 'innerHTML' of null"); // error type when element is not defined myError instanceof Error // true function test(){ var v1 = document.getElementById("myid").innerHTML ="zunu"; // to change with this try { var v1 = document.getElementById("myidd").innerHTML ="zunu"; // exception caught } catch (e) { if (e instanceof Error) { console.error(e.name + ': ' + e.message) // error will be displayed at browser console } } finally{ var v1 = document.getElementById("myid").innerHTML ="Text Changed to Zunu"; // finally innerHTML changed to this. } } </script> <p id="myid">This text will change</p> <input type="button" onclick="test();"> </body> </html>