How to handle error for response Type blob in HttpRequest

后端 未结 5 2000

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条回答
  •  抹茶落季
    2021-01-07 23:33

    I was facing the same issue. In order to handle error response from a blob request you have to parse your error content via FileReader

    This is a known Angular Issue and further details can be read there. You can find different solutions for your problem there as well.

    For Example you can use this function to parse your error in JSON:

      parseErrorBlob(err: HttpErrorResponse): Observable {
        const reader: FileReader = new FileReader();
    
        const obs = Observable.create((observer: any) => {
          reader.onloadend = (e) => {
            observer.error(JSON.parse(reader.result));
            observer.complete();
          }
        });
        reader.readAsText(err.error);
        return obs;
    }
    

    and use it like this:

    public fetchBlob(): Observable {
      return this.http.get(
        'my/url/to/ressource',
        {responseType: 'blob'}
      ).pipe(catchError(this.parseErrorBlob))
    }  
    

提交回复
热议问题