i want to return token from localStorage and catch error.
Observable.of(JSON.parse(localStorage.getItem('currentUser')).token)
.catch((er) => Observable.of(console.log(er))
But it does not catch it. Interesting is when I use try catch method ,I can catch error
try {
return Observable.of(JSON.parse(localStorage.getItem('currentUser')).token);
} catch (er) {
console.log(er);
}
What is the reason of that? Hope someone give advice. Thanks
Because the error is thrown before it's result is passed into Observable.of
. This is unrelated to RxJS, that's how the order of statements is executed by the JS interpreter.
You can do for example:
Observable.defer(() => Observable.of(JSON.parse(localStorage.getItem('currentUser')).token))
.catch(???) // returning Observable.of(console.log(er) is probably useless