简体   繁体   中英

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.

After you've handled your exception (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM