SrAxi
SrAxi

Reputation: 20005

Angular - When to handle errors in Observable's subscription

I have found myself working with code from themes written in latest Angular versions and searching the web, and I have found that the most part of devs don't handle the subscription error.

My question is: When do I have to handle the error in an Observable subscription?

Without error handling:

    this.myService.observable$.subscribe(
        (data) => {
            // do stuff with data
        }
    );

With error handling:

    this.myService.observable$.subscribe(
        (data) => {
            // do stuff with data
        },
        err => {
            // do stuff with error
        }
    );

I mostly find the first version, but...

Isn't an issue not to handle the errors of a subscription?

Doesn't this make the code less solid, testable and more prone to fail?

Upvotes: 3

Views: 4797

Answers (3)

Ashique Razak
Ashique Razak

Reputation: 685

Unrelated to your question, but here's how to handle errors inside subscribe on Angular 16:

this.http.get(url).subscribe(
 {
   next: (data) => 
   {
     //do something
   },
   error: (error) =>
   {
     //handle error
   }
 }
);

Upvotes: 0

mayur
mayur

Reputation: 3618

why is error handling important click Me

Now Lets see Why error handling is necessary in Observables..

Example:

this.service.send(this.shareData).subscribe(() => {

      // Here you are sure that the send has shared the data sucessFully

    }, (error) => {

      /* Now If you want to handle errors Like Front End Errors and Log this
         In your backEnd DB So solve it and fix it */

      /* Example below check error type is It from frontEnd and log error through Api */

      if(error.type !== 'API') {
        this.logService.log({
          Level: 2,
          Message: 'Failed to setFromDB',
        });
      }
    });

Upvotes: 4

JEY
JEY

Reputation: 7123

It's good practices to handle error to give users feedback or fall back to a default behavior.

For instance if you try to contact REST service and communication occurred then you might want to inform the user about connectivity problem or load cached data.

Or if the REST service return an error. For example your application is a booking app and user is doing an order but once he submit the order there is no more item in stock. The REST service return and error and you should display to the user that there is no more items.

Furthermore in the angular style guide:

The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers.

This means that you should return from your service meaningful messages.

Upvotes: 1

Related Questions