如何从数组缓冲区获取错误信息

问题描述 投票:0回答:1

我有以下请求下载一个文件(使用 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 core),我抛出了这样一个执行程序。

throw new DomainException("ErrorMessage");

我可以在devtools的请求中看到,消息中的 "ErrorMessage" 肯定是被送回来了。这是唯一在chrome的响应和预览选项卡中可见的东西。

然而,我似乎在任何地方都找不到那条消息来显示给用户。

通常我可以从 errorResponse.bodyText但这是 undefined 在此


我什么都试过了,从打电话 errorResponse.body, errorResponse.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: 在VueComponent的JSON.parse()处,JSON输入的意外结束。(myMixin.ts:257)

再次尝试以上的方法,但通过在 new Uint8Array(errorResponse.body) 给我

myMixin.ts:257 未抓到(在 promise 中) SyntaxError.Unexpected token N in JSON at position 0 at JSON.parse () at VueComponent: 在VueComponent的JSON.parse()处,在位置0处的JSON中出现了意外的标记N。(myMixin.ts:257)


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

为什么会发生这种情况?

vue.js arraybuffer vue-resource extract-error-message
1个回答
0
投票

我终于找到了我需要的解决方案 此处:

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. 见 这个有用的答案 详见。

© www.soinside.com 2019 - 2024. All rights reserved.