How to handle error for response Type blob in HttpRequest

后端 未结 5 2034

I am calling an http request using httpClient and using response Type as \'blob\' but the problem is when it goes in error block the response type remains \'blob\'.This is c

5条回答
  •  梦毁少年i
    2021-01-08 00:00

    If you're usung RxJS you can use something like this:

    catchError((response: HttpErrorResponse) => {
      return !!this.isBlobError(response) ? this.parseErrorBlob(response) : throwError(response);
    })
    

    and after that you can chain other catchError and do your stuff.

    Here are the methods:

    isBlobError(err: any) {
      return err instanceof HttpErrorResponse && err.error instanceof Blob && err.error.type === 'application/json';
    }
    
    parseErrorBlob(err: HttpErrorResponse): Observable {
      const reader: FileReader = new FileReader();
      const obs = new Observable((observer: any) => {
        reader.onloadend = (e) => {
          observer.error(new HttpErrorResponse({
            ...err,
            error: JSON.parse(reader.result as string),
          }));
          observer.complete();
        };
      });
      reader.readAsText(err.error);
      return obs;
    }
    

提交回复
热议问题