Angular 2+ Http post request responseType blob does not show json errors returned by server

665 Views Asked by At

I have a backend method that return a file (blob). For that I am setting the responseType of angular http post call to blob. Everything works just perfect and file is downloaded successfully. However in case there is an error in server I sent a custom json errror message but the client cannot parse it. I suppose this is an issue because client expects blob.

return this.httpClient.post(`http://myapi.com/mydata/DownloadJob?jobId=${jobId}`, null, { headers, responseType: 'blob' });

I found a similar link that shows how to solve this for Angular 1.x here. I want to do the same in angular 2+. How can this be achieved?

#Update I found this which does exactly what I was looking for

1

There are 1 best solutions below

3
Salketer On

You can create an Error interceptor for your httpClient. This interceptor checks for any error, if there is one and it is served as blob, you can use its .text() method to convert it to text and then JSON.parse() to have it into a usable object.

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
      return next.handle(req).pipe(
        catchError((error: HttpErrorResponse) => {
          const message = JSON.parse(error.error.text());
          return throwError(message);
        })
      );
  }
}

Not too sure, didn't test, but that sounds about right.