Search code examples
angularangular4-httpclient

How to handle failed http put in Angular4


I am looking for best practice guidelines to handle a failed PUT HTTP request in Angular4.

My scenario: a simple component will attempt to update a record by calling an API with a put request.

Example code snippets:

My Component contains this code:

this.workStreamService.save(this.workStream);

This is calling a method on a service called workStreamService which has this code:

save(workStream: WorkStream):  Promise<WorkStream> {
  const url = this.workStreamUrl + '/' + workStream.id;
  return this.http
  .put(url, JSON.stringify(workStream), {headers: this.headers})
  .toPromise()
  .then(() => workStream)
  .catch(this.handleError);
}

The code has been mostly copy-pasted and adapted from the Angular4 tutorial, but the tutorial doesn't go in depth enough to handle errors/successes.

The API does not return a response body, object, or DTO of any kind, just the HTTP status code. 200 for success, 500 if something went wrong.

This is works fine if workStream object passed is OK, and the service is running and does not throw an error. In the circumstances where the service might fail and return a 500, I want to be able to handle this in the component differently to a 200 response. (Example - the component will display either a "success" message, or will show the user a "this call failed" message to prompt them to try again).

I am quite new to Angular4 and cannot find any examples of this kind of handling. Thanks in advance for your help


Solution

  • What does your handleError method do?

    If you either omit this method, or rethrow a Promise.reject() inside of it your error will trickle down to the component and can be consumed in a similar fashion:

    this.workStreamService.save(this.workStream)
      .then(workstream => // Do something on success)
      .catch(() => // Do something on error);
    

    Angular's http methods such as put will deal with the codes for you - if your service receives a success code it'll be translated to a resolved promise (after going through the whole Observable stage), otherwise it'll be translated to a rejected promise for consumption in a .catch.