Search code examples
angularangular-httpclient

How to display httpClient error to user in Angular


My service looks like this:

sortTraceGroups(): Observable<TraceGroup[]> {
    const url = environment.servicesBaseUrl + 'api/trace/sort?sort=' + this.sortChosen;
    return this.httpClient.post<TraceGroup[]>(url, this.traceGroups)
                          .pipe(catchError(this.handleError));
}

private handleError(error: HttpErrorResponse): Observable<never> {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(`Backend returned code ${error.status}, ` + `couldn't get response from server. ElasticSearch is probably down.`);
    }
    return throwError(`Error: couldn't get response from server.`);
  }
}

This is a component which subscribe to http call

onSortChoose(sortChosen: SortChosen): void {
    this.traceService.setSortChosen(sortChosen);
    this.traceService.sortTraceGroups()
      .subscribe(
        traceGroupsSorted => {
          this.traceGroups = traceGroupsSorted;
        },
        (error) => {
          this.error = error;
        }
      );
}

Now I tried to show error message in my html like this

<div *ngIf="error" class="offset-md-3 col-md-6 alert alert-danger row justify-content-center" role="alert">
  {{ error }}
</div>

It works fine when error occurs for the first time.
However when I do another call and it finish successfully I don't want to show the error message anymore. The only solution I come up is to update error message every time I do http call which seems to me incorrect.

onSortChoose(sortChosen: SortChosen): void {
    this.traceService.setSortChosen(sortChosen);
    this.traceService.sortTraceGroups()
      .subscribe(
        traceGroupsSorted => {
          this.traceGroups = traceGroupsSorted;
          this.error = ''; // do I need this line in every http call just to reset error message ?
        },
        (error) => {
          this.error = error;
        }
      );
}

Is there an elegant way to display error in html only when http call fails and don't show when it ends successfully without changing error attribute every time ?
In this example it looks 'okayish' but sometime I need to share error between two components through service and it doesn't seems OK to call setter on service just to changed error message

Thanks


Solution

  • Is there an elegant way to display error in html only when http call fails and don't show when it ends successfully without changing the error attribute every time?

    Nope, you have to unset the property.

    But you can use complete handler for clearing the property instead of the next handler. There are three functions available to send data to the subscribers of the observable:

    1. next: send any value such as Numbers, Arrays or objects to its subscribers.
    2. error: sends a Javascript error or exception
    3. complete: does not send any value
    onSortChoose(sortChosen: SortChosen): void {
      this.traceService.setSortChosen(sortChosen);
      this.traceService.sortTraceGroups()
        .subscribe(
          traceGroupsSorted => {
            this.traceGroups = traceGroupsSorted;
          },
          (error) => {
            this.error = error;
          },
          () => this.error = ''; // do I need this line in every http call just to reset error message ?
        );
    }
    

    Defining observers