gpt4 book ai didi

javascript - 将数组与错误合并为单一类型

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:51 25 4
gpt4 key购买 nike

我有一个基于 Promise 的库(适用于 Node.js 0.10 - 6.x),其方法使用 Array 进行拒绝。

当使用Bluebird时它会导致警告: promise 被拒绝且无错误

将数组包装为自定义错误类型很容易,但我想避免破坏库的向后兼容性。

是否可以实现这样一个可以用作数组的对象,同时被Bluebird看到同时作为 Error 对象?

额外内容

Error 继承时,我使用以下帮助器来与 Node.js 0.10 - 0.12 兼容:

function inherits(child, parent) {
child.prototype.__proto__ = parent.prototype;
}

然后查看Bluebird来源,也许有一种方法可以以某种方式绕过其验证:

Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};

最佳答案

Javascript 不允许真正的多重原型(prototype)继承。

您可以“扩展”Error,但子类不能同时是instanceofErrorArray

如果Bluebird使用duck-typing您可以尝试对 Array 对象进行子类化并模拟 Error 行为(接口(interface)和属性),但这在很大程度上取决于 Bluebird 错误检查实现。

我认为将数组值包装到错误属性/属性中更好、更稳健。

关于javascript - 将数组与错误合并为单一类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37865168/

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