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 { HttpClient } from '@angular/http';
2
import { Injectable } from '@angular/core';
3
import { map, catchError } from 'rxjs/operators';
4
5
@Injectable()
6
export class SearchService {
7
8
constructor(private http: HttpClient) {}
9
10
search(term: string) {
11
return this.http.get('https://api.spotify.com/v1/dsds?q=' + term + '&type=artist')
12
.pipe(
13
map(response => response.json()),
14
catchError((e) => {
15
return Observable.throw(new Error(`${ e.status } ${ e.statusText }`));
16
})
17
)
18
}
19
}
Copied!
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
...
5
6
search(term: string) {
7
return this.http.get(`https://api.spotify.com/v1/dsds?q=${term}&type=artist`)
8
.pipe(
9
map(response => response.json()),
10
catchError(e => {
11
if (e.status >== 500) {
12
return cachedVersion();
13
} else {
14
return Observable.throw(
15
new Error(`${ e.status } ${ e.statusText }`)
16
);
17
}
18
}))
19
20
}
21
}
Copied!
Copy link