Catch and Release

We also have the option of using the .catch operator. It allows us to catch errors on an existing stream, do something, and pass the exception onwards.

  1. import { Http } from '@angular/http';
  2. import { Injectable } from '@angular/core';
  3. @Injectable()
  4. export class SearchService {
  5. constructor(private http: Http) {}
  6. search(term: string) {
  7. return this.http.get('https://api.spotify.com/v1/dsds?q=' + term + '&type=artist')
  8. .map((response) => response.json())
  9. .catch((e) => {
  10. return Observable.throw(
  11. new Error(`${ e.status } ${ e.statusText }`)
  12. );
  13. });
  14. }
  15. }

View Example

It also allows us to inspect the error and decide which route to take. For example, if we encounter a server error then use a cached version of the request otherwise re-throw.

  1. @Injectable()
  2. export class SearchService {
  3. ...
  4. search(term: string) {
  5. return this.http.get(`https://api.spotify.com/v1/dsds?q=${term}&type=artist`)
  6. .map(response => response.json())
  7. .catch(e => {
  8. if (e.status >== 500) {
  9. return cachedVersion();
  10. } else {
  11. return Observable.throw(
  12. new Error(`${ e.status } ${ e.statusText }`)
  13. );
  14. }
  15. });
  16. }
  17. }

原文: https://angular-2-training-book.rangle.io/handout/http/catching-rejections/catch_and_release.html