我有此方法(Angular 9,所以 Typescript ),该方法用于检索新的brend Json Web token 来验证当前用户
getNewAccessToken(){
return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
tap((response:Token) => {
this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
this.isLoggedIn.next(true);
}
}
当我订阅此方法时,我会检查类似的错误
this.authService.getNewAccessToken().subscribe(
res => { //do something with res... },
error => throw error //catch error
);
我可以使用管道和 catchError 在可观察的代码中直接移动错误检测吗?代码将转向此
getNewAccessToken(){
return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
tap((response:Token) => {
this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
this.isLoggedIn.next(true);
},
catchError(error => {
throw error;
})
));
}
我认为这是一种管理可观察错误的集中方式。
通常,对可观察对象或其观察者进行错误处理会更好吗?
这两种方法的优缺点是什么?在性能方面有什么区别吗?
我认为 promise 可以提出相同的问题
最佳答案
是的,将错误处理移入pipe
是一个好习惯,因为它是关注点分离。它将数据检索与数据表示分开。
An example of code of Angular 2 documentation:
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
关于javascript - 可观察或观察者中的错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61791325/