gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:45:54 25 4
gpt4 key购买 nike

我正在使用一个自定义的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com