How to display error message from angular 8 typescript subscribe?

Viewed 709

I have a c sharp backend with the following custom exception:

try
{
  ...
}
catch (UserDetailAlreadyRegisteredException ex)
{
  return BadRequest("The user is already registered");
}   

This exception returns - "The user is already registered" and it works perfectly in the backend.

However when I call it from the front end, it does not display the error message, I only get [object, object]. And when I try to log the object as well, there is nothing useful inside. This is how I call it in the front end:

  onRegisterSubmit(user: User): void {
    this.userService.registerNewUser(user).subscribe(() => {
      this.toastr.success('Registration Completed', 'Success');
    },
      error => {
        // console.log(error._body);
        this.toastr.error(error, 'Failed');
      }
    );
  }

Is there a way to pass the message from the backend to the front end?

1 Answers

you can intercept errors using status codes. Send them in C# backend

c#

try
{
  ...
}
catch (UserDetailAlreadyRegisteredException ex)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return BadRequest("The user is already registered");
}   

service.ts

I am assuming you are using angular 9+. Use RXJS throwError to intercept and send error observable.

    import { throwError } from 'rxjs';
    
registerNewUser(user){

return this._http.post("url", data)
      .pipe(catchError(this.errorHandler));
}


    public errorHandler(errorResponse: HttpErrorResponse) { 
      //write your own error I am returning response as such
        return throwError(errorResponse);
      }

component.ts

onRegisterSubmit(user: User): void {
    this.userService.registerNewUser(user).subscribe(() => {
      this.toastr.success('Registration Completed', 'Success');
    },
      (error) => {
        // console.log(error._body);   **//this block gets activated at error**
        this.toastr.error(error, 'Failed');
      }
    );
  }
Related