简体   繁体   中英

How to get response of failed api

In my api there is some validation, for which it fails and giving me error in my network tab response like this:

{"Message":"not allowed '<' word;"}

But I am not able to show it in my error block of subscribe method. How can i show this on my toastr when api fails or response status code is 400. I tried this:

this.myService
      .saveData(myData)
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        data => {
          this.alertService.success('Record Saved Successfully');
        },
        error => {
          this.spinner.hide();
          this.alertService.error(error.Message);
        }
      );
  }


 private handleError(error: HttpErrorResponse, scope) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened, please try again later.');
  }

According to angular documentation , this change should work.

Create a custom error handler or use default

 private handleError(error: HttpErrorResponse, scope) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened, please try again later.');
  }

Then import it and use:

import { catchError } from ...

...
...
this.myService
      .saveData(myData)
      .pipe(takeUntil(this.unsubscribe))
      .pipe(catchError(this.handleError)).
      .subscribe(
        data => {
          this.alertService.success('Record Saved Successfully');
        }
      );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM