HttpClient - HttpErrorResponse not json but blob

See original GitHub issue

I’m submitting a…


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Not sure if its a bug or intended behavior so can’t check bug although it seems like one.

Current behavior

I am sending http request like this:

return this.http.get(url, {
      observe:'response',
      headers: headers,
      responseType:'blob'
    })

Server responds by 400 Bad Request, application/json content-type header and in body it returns json object:

{
  message: "some error message"
}

error property on HttpErrorResponse is of type Blob.

Expected behavior

I would expect HttpErrorResponse.error property to be json according to content-type server returned since documentation says:

The error property will contain either a wrapped Error object or the error response returned from the server. ref: https://angular.io/api/common/http/HttpErrorResponse

So, if it puts server returned body into HttpErrorResponse.error then it feels like it should obey servers content-type header describing that same body.

Minimal reproduction of the problem with instructions

Use request above.

What is the motivation / use case for changing the behavior?

Environment


@angular/cli: 1.4.2
node: 6.9.3
os: win32 x64
@angular/animations: 4.4.6
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.2
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.3.4



Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:50
  • Comments:15 (5 by maintainers)

github_iconTop GitHub Comments

46reactions
JaapMosselmancommented, Dec 6, 2017

I created this interceptor as a temporary solution until this one is fixed:

@Injectable()
export class BlobErrorHttpInterceptor implements HttpInterceptor {
    public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError(err => {
                if (err instanceof HttpErrorResponse && err.error instanceof Blob && err.error.type === "application/json") {
                    // https://github.com/angular/angular/issues/19888
                    // When request of type Blob, the error is also in Blob instead of object of the json data
                    return new Promise<any>((resolve, reject) => {
                        let reader = new FileReader();
                        reader.onload = (e: Event) => {
                            try {
                                const errmsg = JSON.parse((<any>e.target).result);
                                reject(new HttpErrorResponse({
                                    error: errmsg,
                                    headers: err.headers,
                                    status: err.status,
                                    statusText: err.statusText,
                                    url: err.url
                                }));
                            } catch (e) {
                                console.log(e);
                                reject(err);
                            }
                        };
                        reader.onerror = (e) => {
                            console.log(e);
                            reject(err);
                        };
                        reader.readAsText(err.error);
                    });
                }
                return _throw(err);
            })
        );
    }
}
21reactions
mattforscommented, Jan 10, 2018

Here’s what I did to handle json errors with a blob response type:

  private handleError(err: HttpErrorResponse): void {
    if ('application/json' === err.headers.get('Content-Type')) {
      const reader = new FileReader();
      reader.addEventListener('loadend', (e) => {
        console.log(JSON.parse(e.srcElement['result']));
      });
      reader.readAsText(err.error);
    } else {
      console.log('not json');
    }
  }
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to handle error for response Type blob in HttpRequest
I will suggest a solution that converts the blob to json synchronously. Service class: public doGetCall(): void { this.httpClient.get('/ ...
Read more >
Communicating with backend services using HTTP - Angular
Now HttpClient.get() returns an Observable of type HttpResponse rather than just the JSON data contained in the body. The component's showConfigResponse() ...
Read more >
angular httpclient post return json value - You.com
When I request a JSON from HTTP its returns how I expected, but I cant convert an ... import { HttpClient, HttpErrorResponse }...
Read more >
Angular HttpClient Deep Dive (Headers, HTTP events, non ...
Show non-JSON data. There are always scenarios to download files, BLOB (binary large object) or text from the remote server. An Angular ...
Read more >
Fetch Data from an API using the HttpClient in Angular
Handle HTTP Errors in Angular with HttpErrorResponse ... Fetch non-JSON data by specifying HttpClient responseType in Angular.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found