How to nicely throw an error to an Angular RXJS Observable subscriber

Scott Reece

For the function below, how can I throw an error from the 'BROKEN' like that can be handled nicely by its subscriber in the same way as the 'WORKS' line of code?

What I'm seeing is that the 'Works' line passes the error neatly this function's subscriber, whereas the BROKEN line just blows up without getting handled by its subscriber. I'm using Angular (version 5.0.3) in an Ionic project, RXJS version 5.5.2, and the HttpClient in @angular/common/http.

public makeRequest(requestParameters) {

  return Observable.create(observer => {

    let url = 'http://example.com/service/action?a=b';

    this.http.get(url,{withCredentials: true})
      .subscribe(data => {
        if(data["success"] !== true)
          observer.error("Unexpected result");//BROKEN
        else
          observer.next(data["payload"]);
      },
      err => {
        console.log('error: ' + err);
        observer.error(err);//WORKS
      });
    });
}

Here's an example of a function that calls the one above:

public getStuffFromServer(){
  this.makeRequest({parameters go here}).subscribe(
      data => {
        //do something with the results
      },
      err => {
        //This never gets called from the 'BROKEN' code (but it does from the WORKS code
      }
    );
}

Thanks for your help!

Scott Reece

OK, it looks like I found the answer on this page: https://codingblast.com/rxjs-error-handling/

The key is to use the map and catch functions like so:

public makeRequest(requestParameters) {

return Observable.create(observer => {
let url = 'http://example.com/service/action?a=b';
this.http.get(url,{withCredentials: true})
  .map(data => {
    if(data["success"] !== true)
      throw new Error("Something meaningful");
    return data["payload"];
   })
  .catch(err => {
    return Rx.Observable.throw(err);
   });
  .subscribe(data => {
      observer.next(data);
  },
  err => {
    console.log('error: ' + err);
    observer.error(err);
  });
});
}

Hopefully this will help somebody. Thank you everyone who answered or gave it some thought!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

throw error inside rxjs Observable

how do you throw an error from RXJS Observable retryWhen

How to throw an Observable error

RxJS "throw new Error" vs "Observable.throw"

How to throw error from RxJS map operator (angular)

Angular Universal RxJs "Observable_1.Observable.throw is not a function"

RxJS Observable with asynchronous subscriber function

How to throw observable error manually in angular2?

Angular RxJS Observable loading error

How to throw an observable error manually?

How to keep observable alive after error in RxJS 6 and Angular 6

"rxjs" observable.throw is not a function - Angular4

Module not found: Error: Can't resolve 'rxjs/add/observable/throw'

How can I debug the object type returned to the subscriber of an Angular observable?

Rxjs - clean up observable after subscriber unsubscribes

How to handle error and return observable while subscribe inside an observable function in Rxjs Angular

Angular/RxJS type error when mapping observable

how to throw an error after retrying rxjs 6

Angular 12/Typescript/rxjs: error handling of nested Promises and rxjs Observable

How to return Observable from subscriber?

How to add item in rxjs observable array in angular

How to push to Observable of Array in Angular 4? RxJS

How to update data in Observable in Angular? rxjs

How to call both next and error on RxJS Observable

How to import map property of rxjs in angular project , Error : Property 'map' does not exist on type 'Observable<Object>'?

Why Converting Observable to WritableSignal in Angular 16 throw error of missing properties

Angular / RxJS Multicasting Observable of Observable

Angular/RxJS: synchronous observable

RXJS/Angular Replace Observable

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive