Error Handling

If something unexpected arises we can raise an error on the Observable stream and use the function reserved for handling errors in our subscribe routine to see what happened.

  1. export class App {
  2. values: number[] = [];
  3. anyErrors: Error;
  4. private data: Observable<number[]>;
  5. constructor() {
  6. this.data = new Observable(observer => {
  7. setTimeout(() => {
  8. observer.next(10);
  9. }, 1500);
  10. setTimeout(() => {
  11. observer.error(new Error('Something bad happened!'));
  12. }, 2000);
  13. setTimeout(() => {
  14. observer.next(50);
  15. }, 2500);
  16. });
  17. let subscription = this.data.subscribe(
  18. value => this.values.push(value),
  19. error => this.anyErrors = error
  20. );
  21. }
  22. }

View Example

Here an error is raised and caught. One thing to note is that if we included a .complete()after we raised the error, this event will not actually fire.Therefore you should remember to include some call in your error handlerthat will turn off any visual loading states in your application.

原文: https://angular-2-training-book.rangle.io/handout/observables/error_handling.html