Angular:接收文件的 HTTP 请求中的错误处理

Angular: Error handling in HTTP request to receive a file

提问人:Илья Никитин 提问时间:11/6/2023 更新时间:11/6/2023 访问量:35

问:

我需要向服务器发送请求,如果出现问题,我希望服务器以文件或错误消息进行响应。问题是我正在努力设置我的请求以处理文件和错误。我怎样才能做到这一点?

按需提供服务

  export(id: string, poolsName: string[]): Observable<Blob> {
    return this.http.post<Blob | any>(`${environment.apiUrl}/item/${id}/export`, poolsName)
  }

元件

async fullExport(poolsName: string[]){

    if(this.projectId) {

      this.projectsService.export(this.projectId, poolsName).subscribe(
        (response: any) => {
          console.log("res: ", response);
          // const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
          // const url = window.URL.createObjectURL(blob);
          // const a = document.createElement('a');
          // document.body.appendChild(a);
          // console.log(url);
          // a.style.display = 'none';
          // a.href = url;
          // a.download = 'output.pptx';
          // a.click();
        },
        (error: any) => {
          console.log("error: ", error);
        }
      );
    }

  }

执行请求时,如果它返回一个文件,我会在浏览器控制台中收到此错误

{
    "headers": {
        "normalizedNames": {},
        "lazyUpdate": null
    },
    "status": 201,
    "statusText": "Created",
    "url": "http://localhost:8080/item/6310716b78015e32433ee34d/export",
    "ok": false,
    "name": "HttpErrorResponse",
    "message": "Http failure during parsing for http://localhost:8080/item/6310716b78015e32433ee34d/export",
    "error": {
        "error": {},
        "text": "PK\u0003\u0004\u0014\u0000\b\b\b\u0000�..."
    }
}

我尝试将 { responseType: 'blob' } 添加到 http 请求中,然后正常接收文件,但如果发生错误,我无法接收。

Angular TypeScript 错误处理 httprequest

评论

1赞 Evgeny Gurevich 11/6/2023
>>执行请求时,如果它返回文件,我会在浏览器控制台中收到此错误<< Http 状态 201 不是错误状态。我建议您将所需的功能分为 2 个部分。第一个 - 您的 POST,第二个 - 额外的 GET 请求以获取所需的数据。
0赞 Илья Никитин 11/6/2023
@EvgenyGurevich 但是为什么它被捕获在错误块而不是响应块中呢?
1赞 Илья Никитин 11/6/2023
@EvgenyGurevich 那么,您的意思是在执行 POST 请求后,如果成功,则发出 GET 请求来检索文件?好主意;谢谢。

答: 暂无答案