Angular throwError
January 25, 2024
RxJS throwError
operator is used to create an Observable
that emits an error notification immediately and no element. throwError
can be used composing with other Observable
, such as in a mergeMap
, switchMap
etc. throwError
is introduced in RxJS 6 and we need to use it in place of Observable.throw()
. Angular 6 has integrated RxJS 6 and Angular 6 onwards we can use throwError
that will return Observable
instance with error message. We catch error using catchError
returned by throwError
.
throwError
is imported as following.
import { throwError } from 'rxjs';
throwError
with examples step-by-step.
1. Using throwError
Let us understand how to usethrowError
operator.
Example-1:
In this example, the
Observable
instance will emit 1,2,3,4 but for the number 3, we will throw error.
of(1,2,3,4).pipe( mergeMap(data => { if (data === 3) { return throwError('Error Occurred for data: '+ 3); } return of(data); }) ).subscribe(res => console.log(res), err => console.error(err) );
1 2 Error Occurred for data: 3
Here we will emit numbers after every 2 seconds and for number 2, an error is thrown.
interval(2000).pipe( mergeMap(x => x === 2 ? throwError('Error: Received 2') : of('a', 'b') ), ).subscribe(x => console.log(x), e => console.error(e) );
a b a b Error: Received 2
2. throwError, retry and catchError
Here we will create an example withthrowError
, retry
and catchError
.
of("A", "B").pipe( switchMap(el => { if (el === "B") { return throwError("Error occurred."); } return el; }), retry(2), catchError(err => { console.error(err); return throwError("User defined error."); }) ).subscribe(el => console.log(el), err => console.error(err), () => console.log("Processing Complete.") );
A A A Error occurred. User defined error.
Observable
emits element B, error is thrown by throwError
. The operator retry
resubscribes 2 times and finally error is caught by catchError
operator and then we again throw user defined error using throwError
. Process complete block will not execute because error occurs.
3. JavaScript throw vs RxJS throwError
JavaScriptthrow
statement throws user-defined exception. throw
does not return Observable
instance. Find the sample code snippet for throw
.
switchMap(el => { if (el === "B") { throw new Error("Error occurred."); } return el; })
throwError()
returns Observable
instance that emits only error and no element. Find the sample code for throwError()
.
switchMap(el => { if (el === "B") { return throwError("Error occurred."); } return el; })