W3cubDocs

/RxJS

throwError

function stable

Creates an Observable that emits no items to the Observer and immediately emits an error notification.

throwError(error: any, scheduler?: SchedulerLike): Observable<never>

Parameters

error

The particular Error to pass to the error notification.

scheduler

Optional. Default is undefined.

A SchedulerLike to use for scheduling the emission of the error notification.

Returns

Observable<never>: An error Observable: emits only the error notification using the given error argument.

Description

Just emits 'error', and nothing else.

throw marble diagram

This static operator is useful for creating a simple Observable that only emits the error notification. It can be used for composing with other Observables, such as in a mergeMap.

Examples

Emit the number 7, then emit an error

import { throwError, concat, of } from 'rxjs';

const result = concat(of(7), throwError(new Error('oops!')));
result.subscribe(x => console.log(x), e => console.error(e));

// Logs:
// 7
// Error: oops!

Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2

import { throwError, interval, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

interval(1000).pipe(
  mergeMap(x => x === 2
    ? throwError('Twos are bad')
    : of('a', 'b', 'c')
  ),
).subscribe(x => console.log(x), e => console.error(e));

// Logs:
// a
// b
// c
// a
// b
// c
// Twos are bad

See Also

© 2015–2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/index/function/throwError