2

I'm having a hard time understanding the behavior I get on http calls with errors.

The goal is to have different behaviors based on the error message returned by the server on 403, or 400 responses.

When using Chrome network I can see the message

enter image description here

But when doing a console.log of the error all I get is an ProgressEvent object in the body.

enter image description here

The code in question is quite simple, and the 200 are handled fine with the json returned being accesible.

this.service.myFunction(this.email).subscribe(
        auth => console.log(auth), // works fine
        error => console.log(error) 
    );

I also tried with a catch, on the actual call, but no luck.

this.myFunction.get(url).map(res => res.json())
    .catch( (err: Response) => Observable.throw(err.json()) ); //     throw the error, which is also the object described above

Do you have any idea of what I'm doing wrong?

Thanks

Adrien Pavillet
  • 373
  • 4
  • 9

1 Answers1

2

Try this :

this.service.myFunction(this.email).subscribe(
    auth => console.log(auth), // works fine
    error => console.log(error.text()) 
);

The Angular 2 documentation for Response says that :

The Response's interface is inspired by the Response constructor defined in the Fetch Spec, but is considered a static value whose body can be accessed many times. There are other differences in the implementation, but this is the most significant.

So if .text() no longer send the full response's body you will have to change your server implementation to send a 200 OK and your error message.

I guess the problem is the XMLHTTPRequest's status changes by reading the headers and then Angular's Http library stops reading the body... (Read this)

Community
  • 1
  • 1
Karbos 538
  • 2,977
  • 1
  • 23
  • 34
  • Thanks for your answer I suspected something like this. With .text() I get `{ "isTrusted": true }` so I suspect it's not quite enough :) The best solution would be a 200 with a way to know it's an error then ? – Adrien Pavillet Jan 05 '17 at 14:00
  • 1
    I sometime see API that product only 200 OK and a Json Response object with a status and a message. In my case, it works with error status code and error messages but I can't see the difference with your... Note that you can have different kind of body response according to the server implementation. Angular 2 support `body: string|Object|ArrayBuffer|Blob;` – Karbos 538 Jan 05 '17 at 14:28