如何在调用远程服务时从xhr对象处理net :: ERR_TIMED_OUT

时间:2019-02-28 14:31:56

标签: javascript ajax xmlhttprequest

我有以下使用xhr对象下载文件的angular / rxjs代码

  async download(fileToUpload: UploadedFileMetaData): Promise<Observable<DownloadEvent>> {
    const url = await this.getDownloadUrl(fileToUpload);

    let xhr = new XMLHttpRequest();

    xhr.responseType = 'blob';

    return Observable.create((observer) => {
      xhr.open('GET', url);
      xhr.send();

      xhr.addEventListener('progress', (progress) => {
         // handle progress
      });

      xhr.addEventListener('load', (e: ProgressEvent & { target: { response: Blob } }) => {
        if (e.target['status'] !== 200) {
          observer.error({ state: DownloadState.failure, error: e.target });
        } else {
          observer.next({ state: DownloadState.success, response: e.target.response });
          observer.complete();
        }
      });

      xhr.addEventListener('error', (err) => {
        console.log('upload error', err);

        observer.error({ state: DownloadState.failure, error: err.message });
      });

      xhr.addEventListener('abort', (abort) => {
        console.log('upload abort', abort);

        observer.error({ state: DownloadState.failure, error: 'Transfer aborted by the user' });
      });

      return () => xhr.abort();
    });

发出请求是为了存储青花斑存储,有时我会遇到net::ERR_TIMED_OUT错误。

但是发生此错误并不会触发我当前分配给xhr对象的任何处理程序。

我如何捕捉和处理此问题

0 个答案:

没有答案