1

I am using the angular6 HTTPClient in my service and would like to maintain the next and err paths of the Observable to the subscriber.

e.g. My component looks something like this:

private myFun(query: string) {

    this.myService.login(data).subscribe(next => {

        // Do successful stuff
        console.log('Got the data: ' + next);
    },
    err => {
       // Handle all errors here
       console.error('good luck next time')
    });
}

My service is using a pipe along with the map and catchError.

private findData(in: string): Observable<string> {

    return this.http.post<string>(self.url, '')
        .pipe(
            map( response => {
            //Check the data is valid
            if (this.dataValid(response)){
                     return this.convertedData(response);
            } else {
                throw new Error('failed parsing data');
            }
            }),
            catchError(this.handleError)
        );
  }

I can detect the parsing issue and raise the error via catchError but what I am struggling to understand is how to process the catchError.

The error handler looks like this:

private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
        // Client Side Error
        console.error('Client side error:', error.error.message);
    } else if (error.message === 'failed parsing data') {
        // Client Side Processing Error
        console.error(error.message);
        return throwError(error.message);
    } else {
        // Service Side Error
        console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable error message
    return throwError('failed to contact server');
}

It does the job but I can't help thinking there must be a better, more Angular/RxJS way, of doing this.

What I would have expected is to have hit the 'error.error instanceof ErrorEvent' path of the error handler. I don't understand how the "error: HttpErrorResponse" parameter is being updated - I am just throwing a "new Error('failed parsing data');".

Any advice/suggestions?

1 Answer 1

1

As per your code, it is evident that catchError callback can take either HttpErrorResponse or Error type. So catchError callback input should be either type as any or Error | HttpErrorResponse like this -

private handleError(error: any // or it can be Error | HttpErrorResponse) {

    //now do console.log(error) and see what it logs
    //as per the output adjust your code

    if (error instanceof Error) {
        // Client Side Error
        console.error('Client side error:', error.error.message);
    } else if (error.message === 'failed parsing data') {
        // Client Side Processing Error
        console.error(error.message);
        return throwError(error.message);
    } else {
        // Service Side Error
        console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable error message
    return throwError('failed to contact server');
}
Sign up to request clarification or add additional context in comments.

Comments

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.