Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map http error response [duplicate]

Is there a way to map not only the successful response but also the error?

I want to get a modified error in the subscribe function

request.subscribe(
    response => {
        this.user = response;
    },
    error => {
        this.error = error;
    }
);

I already tried this

let request = this.http.put(url, JSON.stringify(user))
.map(
    response => response.json(),
    error => this.handleError(error) // returns a string
);

but handleError is never getting executed.

Thanks in advance.

like image 545
gerric Avatar asked Feb 29 '16 15:02

gerric


People also ask

What is the HTTP status code for duplicate record?

409 Conflict - Client attempting to create a duplicate record, which is not allowed. 410 Gone - The requested resource has been deleted.

When should we use status code 201 to respond?

The response code of 201 is hence a success status code that indicates that a new resource has been created. The new resource is effectively created before this response code is sent back and the new resource is returned to the body of the message.

What HTTP response status do you return for validation errors?

If the API fails to validate a request, it will respond with a validation error message (JSON or XML) describing the issue. 400: "There was a parsing error." 400: "There was a missing reference." 400: "There was a serialization error."


1 Answers

To map the result of error response, you need to use the catch operator:

let request = this.http.put(url, JSON.stringify(user)).map(
            response => response.json())
          .catch(
            error => this.handleError(error)
        );

The callback specified in the map operator is only called for successful responses.

If you want to "map" the error, you could use something like that:

this.http.get(...)
       .map(...)
       .catch(res => Observable.throw(res.json())

In this case, the mapped error will be provided to the callback defined in the second parameter of the subscribe method.

like image 130
Thierry Templier Avatar answered Sep 30 '22 12:09

Thierry Templier