Wrapping a callback API and listening for errors?

541 views javascript
5

I'm wrapping a callback API like this:

    export function process(data: string): Observable<Result> {
      return Observable.create((observer: Observer<Result>) => {
        call(data, result => {
            if (result.errors) {
              observer.error(result.errors);
            }
            else {
              observer.next(result);  
            }
            observer.complete();
          },
        });
      });
    }

I'd like to be able to call:

process(data).subscribe(data=>doStuffWithData).catch(e=>performErrorHandling);

I've been reading through the documentation on catchError.

The example ends like this:

//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));

So now it looks like we either get the result or the error when subscribing. Is it possible to separate the value from the error with something like this:

process.subscribe(data=>doStuffWithData).catch(e=>performErrorHandling);

answered question

1 Answer

5

Looks like the error handler is passed as the second argument to subscribe now (subscribe(v=>{...}, e=>handleTheError):

result.subscribe(v=>console.log(v), error=>console.log(error));

For more information see rxjs-error-handling from Angular University.

Here's their HTTP example:

http$.subscribe(
  res => console.log('HTTP response', res),
  err => console.log('HTTP Error', err),
  () => console.log('HTTP request completed.')
);

posted this

Have an answer?

JD

Please login first before posting an answer.