0

我有以下下载文件的请求(使用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: VueComponent 的 JSON.parse () 处的 JSON 输入意外结束。(myMixin.ts:257)

再次尝试上述但传递new Uint8Array(errorResponse.body)给我

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


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

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

4

1 回答 1

2

我终于在这里找到了我需要的解决方案:

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

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

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

另请注意,由于我的响应正文有奇数个字符,我必须使用Uint8Array而不是Uint16Array. 有关详细信息,请参阅此有用的答案

于 2020-06-16T20:51:38.063 回答