throw error inside rxjs Observable
Asked Answered
R

4

23

I'm trying to throw an error inside a rxjs Observable

 new Observable(subscriber => {
   Observable.throw("error1");
   return Observable.throw("error2");
 })
 .subscribe(
   () => {},
   err => console.error(err)
 );

error 1 is not caught.

error2 gives a compilation error:

Argument of type '(this: Observable<{}>, subscriber: Subscriber<{}>) => ErrorObservable<string>' is not assignable to parameter of type '(this: Observable<{}>, subscriber: Subscriber<{}>) => TeardownLogic'. Type 'ErrorObservable<string>' is not assignable to type 'TeardownLogic'

what is the proper way to throw an error inside an observable?

Ratel answered 15/2, 2017 at 11:4 Comment(2)
try throwing an error like Observable.throw(new Error("error1")).Lenee
@JyothiBabuAraja doesn't work. It isn't caught by the subscribe()Ratel
S
20

Use Subscriber.error:

new Rx.Observable(subscriber => {
  subscriber.error("error1");
  subscriber.error("error2"); // not called because a stream will be finalized after any error
})
.subscribe(
  () => {},
  err => console.error(err)
);
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
Symphony answered 15/2, 2017 at 11:21 Comment(0)
T
7

When using new Observable() or Observable.create() you can push the error directly to the subscriber (observer):

Observable.create(subscriber => {
   subscriber.error(new Error("error1"));
 })
 .subscribe(
   () => {},
   err => console.log(err.message)
 );

The anonymous function passed to new Observable() can optionally return an unsubscribe callback. That's why it gives you the error because you're returning an Observable.

Using Observable.throw("error1") is usually not necessary. This is just an Observable that only emits an error and nothing more. You could use it for example like the following:

Observable.create(subscriber => {
    subscriber.next('whatever');
  })
  .merge(Observable.throw(new Error("error2")))
  .subscribe(
    () => {},
    err => console.log(err.message)
  );

See live demo: https://jsbin.com/fivudu/edit?js,console

Talebearer answered 15/2, 2017 at 11:28 Comment(1)
so are thrown errors inside a producer throw new Error() are effectively ignored and not reported?Deoxyribose
A
5

In v6 and higher you want to import throwError, that Observable.throw static method is an unfortunate necessity leftover from v5 compat.

import { throwError } from 'rxjs';
throwError('hello');

Source: https://github.com/ReactiveX/rxjs/issues/3733#issuecomment-391427430

Affable answered 19/5, 2020 at 10:24 Comment(0)
A
2

With an observable you created yourself, you have access to the observer.error() method.

const obs = Observable.create(observer => {

  // Emit a value.
  observer.next("hello");

  // Throw an error.
  observer.error("my error");

});

Note: if you're using RxJS 4, you'll have to use onNext() and onError() instead.

Anagnos answered 15/2, 2017 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.