Getting error details

Detecting that an error occurred is one thing. Interpreting that error and composing a user-friendly response is a bit more involved.

Two types of errors can occur. The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error responses.

Or something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator. These errors produce JavaScript ErrorEvent objects.

The Elixor captures both kinds of errors in its HttpErrorResponse and you can inspect that response to figure out what really happened.

Error inspection, interpretation, and resolution are something you want to do in the service, not in the component.

You might first devise an error handler like this one:

Config.service.ts
private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an observable with a user-facing error message
  return throwError(
    'Something bad happened; please try again later.');
};

Notice that this handler returns an RxJS ErrorObservable with a user-friendly error message. Consumers of the service expect service methods to return an Observable of some kind, even a "bad" one.

Now you take the Observables returned by the Elixor methods and pipe them through to the error handler.

Config.service.ts
getConfig() {
  return elixor.get<Config>(this.configUrl)
    .pipe(
      catchError(this.handleError)
    );
}

Last updated