Search code examples
javascriptangulartypescriptes6-promise

Catch error in promise from a service in an Angular component


Hi everyone running into a problem with a post service I created in angular. Struggling to catch the error from my component when I call the service. I was able to catch the error from the service but I need to do this from my component to properly handle the error. Any advice would be greatly appreciated.

Service

sendData(obj) {
 let promise = new Promise((resolve) => {
   this.http.post(this.URL, obj, this.httpOptions)
     .toPromise()
     .then(
      res => {
        console.log(res);
        resolve(res);
      }
     )
     //.catch((err) => { 
     //  console.log(err);
     //  throw err;
     //});
   });
  return promise;
}

Component

this._myservice.sendData(this.myobj)
  .then(function (res) {
    console.log('data sent');
  })
  .catch(error => {
      console.warn('from component:', error);
      // this console warn never gets logged out
  });

Do I need to update something in my service to allow me to catch the error from the component?


Solution

  • You're creating your own Promise here, but you never call reject if the Promise you're wrapping rejects (throws an error). This is known as the the new Promise antipattern. In your case, you can simply remove this wrapper and replace the call to resolve with a return in order to achieve what you need, like so:

    sendData(obj) {
        return this.http.post(this.URL, obj, this.httpOptions)
            .toPromise()
            .then(res => {
                console.log(res);
                return res;
            });
    }
    

    In order to provide more context, you could fix your original problem by calling reject. This would look like this:

    // DONT'T DO THIS
    sendData(obj) {
       let promise = new Promise((resolve, reject) => {
           this.http.post(this.URL, obj, this.httpOptions)
               .toPromise()
               .then(res => {
                   console.log(res);
                   resolve(res);
                })
                .catch((err) => { 
                    console.log(err);
                    reject(err); // Here.
                });
            });
        return promise;
    }
    

    But, as I said above, this is overcomplicated and unnecessary. I hope that it demonstrates how the Promise your component has access to could never see errors that occurred in the HTTP call.