Angular 13 throw specific error message from backend

Viewed 1117

I have an application (back+front). I'm a newbie in angular and frontend, and I want to know how to get the specific message of error from the backend

When I create a person and I write his email as an invalid email in the backend I get this: enter image description here

In my angular app i have errorHandler:

errorHandler(error:any) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = Error Code: ${error.status}\nMessage: ${error.message};
    }
    return throwError(errorMessage);
  }

which i catch in my create method:

create(user:User): Observable<any> {
    return this.httpClient.post(this.apiURL + 'api/user/', JSON.stringify(user), this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }

I connected toastr to display some message if the operation is successfull or not:

  submit() {
    console.log(this.form.value);
    this.messageService.create(this.form.value).subscribe((res: any) => {
      this.toastr.success("Created successfully!");
      console.log('Post created successfully!');
      this.router.navigateByUrl('messages').then(r => console.log(r));
    },
      (error)=>{
      void this.toastr.error(error.messageType,"We have an error! Something went wrong")
      })
  }

enter image description here

But I get only static message that something is wrong, and I need to get the specific message from my backend(if the username is already taken, or the email is invalid)

When i write error with toastr:

(error)=>{
      void this.toastr.error(error,"We have an error! Something went wrong")
      })

I get this: enter image description here

1 Answers

First of all, it's always safer to pass a closure instead of function reference where this is involved:

catchError(err => this.errorHandler(err))

Secondly, throwError() must be given an error factory and not a constant value, like:

throwError(() => errorMessage);

Thirdly, I'm not sure what exactly you expect to see, but you do nothing with error in your submit() call, did you mean something like this?

error => this.toastr.error(error.messageType, `We have an error: ${error}`)
Related