Joel Christ
Joel Christ

Reputation: 31

Intercepting Observable.throw using .catch while doing async operations inside the .catch

I want to change the error I get from sending a HTTP post request by transforming it into another error. Unfortunately, this operation is asynchronous (it does some translations). I can't seem to get it to rethrow the newError from inside catch callback. Any help?

See example below:

public createShorty(shorty: Shorty): Observable<Shorty> {
  const shortyEndpoint = environment.shortyEndpoint;
  const url = `${shortyEndpoint}/shorties`;
  return this.http.post<Shorty>(url, shorty).catch(err => {
    this.errorHandler.transform(err).subscribe(newErr => {
      Observable.throw(newErr);
    });
  });
}

Upvotes: 1

Views: 61

Answers (1)

martin
martin

Reputation: 96949

If you just want to transform the error to another object you can't do it inside subscribe because you want the new error to be passed down the chain.

Instead inside catch run this.errorHandler.transform and turn its result into an error notification:

return this.http.post<Shorty>(url, shorty)
  .catch(err => this.errorHandler.transform(err) // I'm assuming this returns an Observable
    .map(newError => {
      throw newError; // Rethrow the error so it'll be passed down as an `error` notification.
    })
  );

Upvotes: 2

Related Questions