throw error inside rxjs Observable
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
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
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.
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>