【问题标题】:How to get error message from array buffer如何从数组缓冲区获取错误消息
【发布时间】:2020-10-06 13:46:20
【问题描述】:

我有以下下载文件的请求(使用vue-resource):

this.$http.get(fileUrl, { responseType: 'arraybuffer' }).
    then(
        (response) => {
            let blob = new Blob([response.data], { type: response.headers.get('content-type') });
            let link = document.createElement('a');
            link.setAttribute("type", "hidden");
            link.href = window.URL.createObjectURL(blob);
            let disposition = response.headers.get('content-disposition');
            let matches = /.*filename=(.*);.*/.exec(disposition);
            let filename = (matches != null && matches[1])
                ? matches[1]
                : 'file';
            if (filename.startsWith('"')
                && filename.endsWith('"')) {
                filename = filename.substr(1, filename.length - 2);
            }
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            link.remove();
        },
        (errorResponse) => {
            // TODO: errorResponse doesn't actually have the error message somehow
            console.error(errorResponse);
        });

在我的后端(C# asp.net 核心)中,我正在抛出这样的执行:

throw new DomainException("ErrorMessage");

我可以在 devtools 的请求中看到消息 "ErrorMessage" 肯定会被发回。这是 chrome 的响应和预览选项卡中唯一可见的内容。

但是,我似乎无法在任何地方找到该消息以显示给用户。

通常我会从errorResponse.bodyText 那里得到它,但在这种情况下是undefined


我已经尝试了所有方法,从调用errorResponse.bodyerrorResponse.bodyText(一切都给我undefined),甚至尝试阅读它

var decodedString = String.fromCharCode.apply(null, errorResponse.body);
var obj = JSON.parse(decodedString);
var message = obj['message'];

这只会引发更多错误:

myMixin.ts:257 Uncaught (in promise) SyntaxError: Unexpected end of JSON input 在 JSON.parse() 在 Vue 组件。 (myMixin.ts:257)

再次尝试上述方法,但传入new Uint8Array(errorResponse.body) 给了我

myMixin.ts:257 Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0 在 JSON.parse() 在 Vue 组件。 (myMixin.ts:257)


删除, { responseType: 'arraybuffer' },我可以看到错误信息存在于errorResponse.bodyText

为什么会这样?我怎样才能得到错误消息 - 我可以在网络选项卡中看到它显然确实存在 - 并将其记录在控制台上?

【问题讨论】:

    标签: typescript vue.js arraybuffer vue-resource extract-error-message


    【解决方案1】:

    我终于找到了我需要的解决方案here

    let message = String.fromCharCode.apply(null, new Uint8Array(errorResponse.body));
    

    但是,因为我使用的是 TypeScript,所以我收到了一些关于 errorResponse.body 不能分配给类型 number[] 的烦人消息,所以我这样做:

    let message = String.fromCharCode.apply(null, new Uint8Array(errorResponse.body) as any);
    

    还请注意,由于我的响应正文包含奇数个字符,因此我必须使用 Uint8Array 而不是 Uint16Array。详情请见this helpful answer

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2014-12-11
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      相关资源
      最近更新 更多