Rxjs?中處理錯誤和抓取錯誤的代碼案例
使用 Rxjs
,對于初學者來說,當我們處理 observables
錯誤的時候容易疑惑,因為我們會考慮使用 try-catch
方式捕獲。但是,Rxjs
是通過操作符來管理錯誤。
我們通過代碼案例一步步來了解。案例是使用 angular httpClient
模塊來講解,當然這適用于任何數據流。
場景
我們的應用中使用了一個服務,用來獲取啤酒列表數據,然后將它們的第一個數據作為標題展示。
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable() export class BeerService { private apiUrl = 'https://api.punkapi.com/v2/beers'; constructor(private http: HttpClient) {} getBeers(): Observable<any> { return this.http.get(this.apiUrl); } }
應用的組件訂閱了它,展示啤酒列表,然后獲取其第一條數據。
import { Component, OnInit } from '@angular/core'; import { BeerService } from './beer.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { title = 'my first beer'; beers = []; constructor(private beerService: BeerService) {} ngOnInit() { try { this.beerService.getBeers().subscribe((beers) => { console.log(beers); this.beers = beers; this.title = beers[0].name; }); } catch (err) { this.title = 'Ups a error'; } } }
如果 API
錯誤了會發(fā)生什么呢?我們將該 URL
改成一個錯誤的 URL
,通過某種策略來捕獲錯誤。
使用 try-catch
在 Javascript
中,我們使用 try-catch 來驗證代碼片段,如果某些片段出錯了,我們就會捕獲到它。
但是,在 rxjs
中,try-catch
沒用效果。因為錯誤是發(fā)生在訂閱范圍(subscribe scope),所以 try-catch
解決不了什么,我們需要使用 Rxjs
操作符。
export class AppComponent implements OnInit { title = 'my first beer'; beers = []; constructor(private beerService: BeerService) {} ngOnInit() { try { this.beerService.getBeers().subscribe((beers) => { console.log(beers); this.beers = beers; this.title = beers[0].name; }); } catch (err) { this.title = 'Us a error'; } } }
訂閱中誰抓取錯誤
理解 try-catch
為什么不起作用,記住,當我們訂閱第一個 observable
的時候,訂閱會調起三個可選的參數。
this.beerService .getBeers() .subscribe({ next: (beers) => { console.log(beers); this.beers = beers; this.title = beers[0].name; }, error: (e) => { console.log(e); this.title = 'ups'; }, complete: () => console.log('done'), });
next
:數據流被成功捕獲調用error
:發(fā)送一個Javascript
錯誤或者異常complete
當數據流完成時候調用
所以,錯誤是發(fā)生在訂閱函數的區(qū)域,所以我們怎么出了呢?
使用 Rxjs 的操作符
Rxjs
提供了一些操作符幫助我們處理這些錯誤,每個都可以使用在這些場景中,我們來了解下。
我們將接觸 catchError
,throwError
和 EMPTY
。
catchError
catchError
抓取錯誤,但是會發(fā)出值。簡而言之,它在錯誤的基礎上返回另一個 observable
。
我移除上面提到的三個回調函數的策略,然后配合管道來使用 catchError
操作符。
更多相關 pipe
this.beerService .getBeers() .pipe(catchError(() => of([{ name: 'my default beer' }]))) .subscribe((beers) => { console.log(beers); this.beers = beers; this.title = beers[0].name; });
如果我們的代碼中錯誤時候需要調用其他內容,
catchError
非常適合發(fā)出默認值,并且訂閱可以將默認值拋出去。
throwError
有時候,我們不想拋出錯誤,但是想要提示錯誤信息。針對這個場景,throwError
很適合我們。
throwError
不會觸發(fā)數據到 next
函數,這使用訂閱者回調的錯誤。我們我們想捕獲自定義的錯誤或者后端提示的錯誤,我們可以使用訂閱者中的 error
回調函數。
ngOnInit() { this.beerService .getBeers() .pipe( catchError(() => { return throwError(() => new Error('ups sommething happend')); }) ) .subscribe({ next: (beers) => { console.log(beers); this.beers = beers; this.title = beers[0].name; }, error: (err) => { console.log(err); }, }); }
更多相關 throwError
EMPTY
有時候,我們不想在組件中傳播錯誤。Rxjs
提供了 EMPTY
常量并返回一個空的 Observable
,并未拋出任何的數據到訂閱著回調中。
this.beerService .getBeers() .pipe( catchError(() => { return EMPTY; }) ) .subscribe({ next: (beers) => { this.beers = beers; this.title = beers[0].name; }, error: (err) => console.log(err), });
更多相關 EMPTY
總結
本文,我們學習了如何使用 catchError
在數據流中抓取錯誤,怎么去修改和返回 observable
,或者使用 EMPTY
不去觸發(fā)組件中的錯誤。
本文是譯文,采用意譯的形式。原文地址這里
到此這篇關于Rxjs 中怎么處理和抓取錯誤的文章就介紹到這了,更多相關Rxjs 錯誤處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
淺談Vue3.0之前你必須知道的TypeScript實戰(zhàn)技巧
這篇文章主要介紹了淺談Vue3.0之前你必須知道的TypeScript實戰(zhàn)技巧,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09由document.body和document.documentElement想到的
不知道大家對這個標題有沒有想法,反正此前我一直把他們混為了一談。其實不然,首先需有個“標準”的概念。2009-04-04