2

I need advise for handling errors in front-end of web application. When I call a service to get the community according to community in web app, I want it to catch an error. For example for catching errors like 404.

There is a service for getting community according to id provided.

 getCommunity(id: number) {
        return this.http.get(`${this.api}/communities/` + id + ``);
    }

that is called in events.ts file

 setCommunityBaseUrl() {
        this.listingService.getCommunity(environment.communityId).subscribe((data: any) => {
            this.communityUrl = data.url + `/` + data.domain;
        });
    }

The id is provided in environment. Let's say there are 20 communities in total. When I provide id = 1 the events according to community = 1 appears.

export const environment = {
    production: ..,
    version: 'v2',
    apiUrl: '...',
    organization: '...',
    websiteTitle: '...',
    communityId: 1,
    googleMapsApiKey: '...'
};

The problem is that when I provide id = null all community events are occurring | all events list in the backend is occurring.

Please, help ^^

2 Answers 2

1

When you subscribe you subscribe with an Observer pattern. So the first function you pass in

.subscribe(() => {} );

fires when the Observable calls .next(...)

and after that you can provide another function which will fire whenever the Observable calls .error(...)

so

.subscribe(() => {}, (error) => { handleTheError(error); } );

The this.http.get(...); returns an Observable which will fire the .error(...) on http error

We also know that this.http.get(...) completes or "errors" and it's not an endless one (a one that never completes). So you can make it a promise and manipulate on it promise like.

async getMeSomething(...) { 
   try {
     this.mydata = await this.http.get(...).toPromise();
   }
   catch(error) { 
     handleTheError(error) 
   }
}

But what I really recommend is to use Swagger for your backend and then generate the API Client class with NSwagStudio so you don't have to write the client manually or adjust it or deal with error catching. I use it all the time and it saves us an enormous amount of time

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for such useful info and answer. I will try the options you gave with front - end part as I am responsible for this. Backend is already fixed, it's also written by others. Have a nice day!
0

Because you are using ".subscribe" you can create your own error handler and catch the errors like this, directly on the method.

This is an example on how you can use this:

constructor(
    private _suiteAPIService: SuitesAPIService,
    private _testcaseService: TestcaseService,
    public _tfsApiService: TfsApiService,
    private _notificationService: NotificationService) { }

  errorHandler(error: HttpErrorResponse) {
    return observableThrowError(error.message || "Server Error")
  }

  public something = "something";
  
  GetTestcasesFromSuiteSubscriber(Project, BuildNumber, SuiteId) {
    this._suiteAPIService.GetTestResults(Project, BuildNumber, SuiteId).subscribe(
      data => {
        console.log(data);
        this._testcaseService.ListOfTestcases = data;
        //Notofication service to get data. 
        this._notificationService.TestcasesLoaded();
      },
      error => {
        //Here we write som error 
        return this.something;
      }
    );
  }

1 Comment

Are the services in constructors are self written services (not Angular built in services)? Also, do you mean Observable.throw(error.message || "Server Error") by observableThrowError(error.message || "Server Error") ? Thank you for answer beforehand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.