javascript - 在 javascript 中解释自定义 Error 对象并与之交互

标签 javascript error-handling exception-handling

我正在使用一个自定义的 JavaScript 模块,它有自己的 Error对象。我想拦截那些自定义错误对象并在我的 try{} catch{} 中采用适当的路径 block ,将它们与 Javascript 的内置错误对象(例如 ReferenceError)区分开来, TypeError等等

所以有点像这样。

try {
    // Some code that might produce a traditional javascript error
    // or one of the errors raised by the module I am using.
}catch (error){
    if(error instanceof ExchangeError){
        // Handle this in a way.
    }else{
        // Probably one of the built in Javascript errors,
        // So do this other thing.
    }
}

所以,在上面的例子中,ExchangeError是属于该特定模块的自定义错误,但是,我无法运行 instanceof关于我的错误,尽管当我这样做时 error.constructor.name我得到 ExchangeError .

我的 javascript 范围根本不知道 ExchangeError .所以问题是,我怎样才能拦截那些错误对象呢?我确定我可以通过字符串匹配来做到这一点,但只是想检查是否有更优雅的方式。

我试过的一件事,我有自己的 errors模块,其中有一些自定义错误,我试图模仿模块的错误对象:
    class ExchangeError extends Error {
        constructor (message) {
            super (message);
            this.constructor = ExchangeError;
            this.__proto__   = ExchangeError.prototype;
            this.message     = message;
         }
     }

并通过我的errors 导入模块,但这显然不起作用。

最佳答案

通过实际实现我自己的ExchangeError我实际上做了一些非常糟糕的事情,我蒙蔽了 instanceof用我自己的ExchangeError检查,而 ExchangeError来自模块的实例不是我自己的 ExchangeError 的实例。这就是为什么我的if支票陷入了沉默。

解决方案就是这样做:

     const { ExchangeError } = require ('ccxt/js/base/errors');


从模块中导入错误。现在instanceof查找正在工作。我不知道可以从这样的模块中导入点点滴滴。

感谢@FrankerZ 指出这一点。

关于javascript - 在 javascript 中解释自定义 Error 对象并与之交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54680547/

相关文章:

java - 此语言级别不支持多捕获

javascript - 面包屑的动态宽度

javascript - 我无法从另一个成员函数中读取成员变量

exception - 在我自己的异常类中获取异常行

c# - 在 C# 中混合错误和异常

python - 调用 sys.exit() 和抛出异常的区别

javascript - 通过多个 php 文件通过 javascript POST 数据

javascript - 在 ES6 中调用在文件中导出的函数

php Mysql错误未知ID

node.js - 为什么在此NodeJS异步函数中未捕获错误?