Search code examples
angularhttprxjs6

when httpClient fails it returns an observable error in the error callback instead of an error object


Using the typical HttpClient service for angular 6, I am struggling to retrieve the error output as an object in the error callback, instead its an observable.

   ...
    }, (e) => {
       HttpErrorHandling.process(e, this.messageService, this.loggerService, () => {
       this.messageService.send(NotificationMessage['USER_REGISTRATION_TECHNICAL_ERROR'], MessageTypes.error);
       });
     });
   });

This does not suit my case when I want to retrieve the error status, when I attempt to get it with err.status, it is undefined because I am doing it on an observable

class HttpErrorHandling

 public static process(err: HttpErrorResponse, messageService: MessageService, logger: LoggerService, callback: any) {
    switch(err.status) {
      case HttpStatusCodeEnum.HttpFailure: {
        // Http failure, no internet connection
        this.handleError(err.name, logger, null);
        break;
      }
    ...

if instead I subscribe to the error observable like so, I do retrieve the error as an object, but this is messy and bad for performance (nested subscribes). Is there another way to approach this?

     }, (e) => {
    e.subscribe(
          err => HttpErrorHandling.process(err, this.messageService, this.loggerService, () => {
            this.messageService.send(NotificationMessage['USER_REGISTRATION_TECHNICAL_ERROR'], MessageTypes.error);
          })
        });
      });
    });

Solution

  • In short what I failed to see was that someone changed how we should return an error, without testing behind the implications, because who really test failed http request if not explicitly expressed to the QA. Anyways someone decided to return the error like so for the service I was using elsewhere in the code:

    catchError((err) => {
              throw of(err);
            })
    

    all I had to do is was remove the of method and just return err instead. Not sure why people would return errors as observables.