Euridice01
Euridice01

Reputation: 2568

How can I prevent throwing errors in errorhandler?

Currently, in one of my service methods, I have something like this:

this.get(foo).catch((e) => this.errorHandler(e));

Where errorHandler is:

errorHandler(error: HttpErrorResponse) {

    if (error.status === 422) {
      this.openSnackBar('Number already exists');
      return Observable.throw(error.message || 'Server Error');
    } else {
      return Observable.throw(error.message || 'Server Error');
    }
  }

While this works just fine, it throws the error and I can see it reported in my console window. I was wondering for situations where I am handling the error in a user friendly message like the snackbar example above, how can I prevent it from being thrown/shown in the console window?

I just want to catch the error, check the status and return a snackbar with userfriendly message. I have noticed if I remove the throw above, the code stops working.

Upvotes: 1

Views: 598

Answers (1)

Klaas Cuvelier
Klaas Cuvelier

Reputation: 301

After you've handled your exception (e.g. by showing an alert, toast or whatever), return an Observable.empty() instead of Observable.throw. Observable.empty is an observable that "completes" immediately, without "next"ing any values; this will stop your observable stream correctly.

Upvotes: 3

Related Questions