gpt4 book ai didi

javascript - 可观察或观察者中的错误处理?

转载 作者:行者123 更新时间:2023-12-03 07:52:23 25 4
gpt4 key购买 nike

我有此方法(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com