【问题标题】:Exception 'illegal buffer' thrown in protobufjsprotobufjs 中抛出异常“非法缓冲区”
【发布时间】:2020-08-15 16:18:18
【问题描述】:

我正在使用 protobufjs 通过 API 管理我的数据。它在大多数情况下都能完美运行,但在一个消息实例中,我得到一个“非法缓冲区”异常。这是由库中的一些内部代码引发的。我在这里粘贴 Chrome 调试器视觉效果,同时在 throw 语句的断点处停止。 Chromer debugger output

如您所见,Chrome 告诉我缓冲区确实是一个 Uint8Array(755 字节)。为什么 if 语句解析为 false 并导致 throw 语句被执行? "buffer instanceof Uint8Array" 和 "Array.isArray(buffer)" 都是真的。

更新

我写了一些代码(无意中从 protobufjs 复制并简化了它):

function test() {
    var data = new Uint8Array([10, 9, 18, 7, 99, 111, 110, 110, 101, 99, 116, 16, 1]);
    testProtobuf(data);
}

function Reader(buffer) {
    this.buf = buffer;
    this.pos = 0;
    this.len = buffer.length;
}

var create_array = function (buffer) {
    console.log(buffer);
    if (buffer instanceof Uint8Array || Array.isArray(buffer))
        return new Reader(buffer);
    throw Error("illegal buffer");
}

function testProtobuf (data) {
    try {
        create_array(data);
    }
    catch (e) { console.log('Exception')};
}

当我调用 test() 时,它会调用 testProtobuf,而 testProtobuf 又会调用 create_array,不会引发异常。我还在实际代码中从我的 onmessage 方法调用 testProtobuf。在这种情况下,仍然会抛出异常。如您所见,我在控制台上记录缓冲区。两个日志是相同的(我确保测试数据相同)。

这是 Chrome 控制台: Console output in Chrome

【问题讨论】:

  • 有没有可能是来自另一个领域(框架等)的Uint8Array 实例?
  • ""buffer instanceof Uint8Array" 和 "Array.isArray(buffer)" 都是真的。" - 好吧,显然不是,你为什么做出这个假设?
  • 另一个领域?你是什​​么意思?对于假设:我之所以这样做是因为抛出了异常(抛出状态的断点是 Chronme 停止的地方),而对于其他消息,它不会被抛出。显然这与缓冲区或其数据有关,但我无法弄清楚。
  • 你能创建一个minimal reproducible example 来演示这个问题吗?
  • 更新了主要问题以添加一些代码。然而,测试代码并没有失败,尽管数据与代码失败时的数据相同。

标签: javascript protobufjs


【解决方案1】:

我找到了解决这个问题的方法here

Sample.deserializeBinary(Array.from(buffer));

还有一个来自我的打字稿代码的例子:

const arrayBuffer = await res.arrayBuffer();
const array = new Uint8Array(arrayBuffer);
const response: Uint8Array = (Array.from(array) as unknown) as Uint8Array;
rpcImplCallback(null, response);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多