How to get body from HttpErrorResponse in Angular 6?

后端 未结 5 827
予麋鹿
予麋鹿 2020-12-11 17:14

I have created a REST API call in my Angular app which downloads a file.

I am setting responseType to \'blob\' since I am expecting a file in response.

But w

5条回答
  •  情书的邮戳
    2020-12-11 17:32

    You could try a separate error handler function, which returns the response as T as follows -

    public handleError(operation = 'operation', result?: T) {
        return (error: any): Observable => {
    
            // TODO: send the error to remote logging infrastructure
            console.error(error); // log to console instead
    
            // TODO: better job of transforming error for user consumption
            console.log(`${operation} failed: ${error.message}`);
    
            // Let the app keep running by returning an empty result.
            return of(result as T);
        };
    }
    

    Then simply use it to track errors in your request as follows -

    return this.http.post(this.appconstants.downloadUrl, data, { responseType: 'blob' }).pipe(
        map(this.loggerService.extractFiles),
        catchError(this.loggerService.handleError('downloadFile'))    // <----
    );
    

    FYI, the function extractFiles that I used above to return a file is as follows -

    public extractFiles(res: Blob): Blob{
        return res;
    }
    

提交回复
热议问题