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

标签 javascript error-handling promise rxjs observable

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

相关文章:

javascript - 失败的 Promise 被 Application.onerror 函数捕获

javascript - Angular 6 Material MatFormField 显示为未知组件

javascript - 简单的 Canvas 矩形与 Javascript 交互

javascript - 限制选中的复选框数量

java - Javax : ErrorListener not called when transforming a fo file into a pdf

javascript - 使用 Dexie 和 Svelte 从 IndexedDB 中检索值

javascript - 用 ; 分隔的单词转换字符串的最快方法是什么?成套?

jquery - 在提交jquery上添加适当的错误消息

android - 如何防止EditText错误图标被填充插入?

javascript - NodeJS - 循环内的延迟函数