user11352561
user11352561

Reputation: 2637

Angular - How to pass custom error message from restful api to Angular frontend

In my Angular-11 application, I have these codes:

login.ts:

  onSubmit(){
    this.isSubmitted = true;

    // stop here if form is invalid
    if (this.loginForm.invalid) {
          return;
      }

    const formData = this.loginForm.getRawValue();

    const data = {
      email: formData.email,
      password: formData.password
    };
    const headers = {
      'Content-Type' : 'application/json'
    };

    this.isLoading = true;
    return this.api.post('login', data, headers)
      .pipe(first())
      .subscribe(
        data => {
          this.tokenHandler(data);
        },
        error => {
          this.toastr.error(error.message);
          this.isLoading = false;
        });
  }

tokenHandler function:

  tokenHandler(data: any){
    this.token.setRoles(data.results.user.roles);
    this.token.set(data.results.token_type + ' ' + data.results.access_token, data);
    this.auth.changeAuthStatus(true);
      this.router.navigateByUrl('/dashboard');
  Swal.fire({
    position: 'center',
    icon: 'success',
    title: data.message,
    showConfirmButton: false,
    timer: 3000
  });

  }

These are my json api responses from backend for both login success and failure:

login success:

{
  "message": "You have successfully Logged In.",
  "error": false,
  "code": 200,
  "results": {
    "user": {
        "id": 2,
        "name": null,
        "email": "[email protected]",
    }
  }
}

login failure:

{
  "success": false,
  "message": "Email is Required!",
  "data": []
}

It works fine when login is successful. It displays the message from the backend api JSON response as instructed here:

title: data.message,

But for the failure or error, it keeps bringing the same message "Internal Server Error". But the customised message from backend api JSON response, like: "Email is required" as in the endpoint

"message": "Email is Required!",

When I did this from Angular:

this.toastr.error(error.message);

How do I get this required and have the custumized message from the api response instead of

"Internal Server Error" message

Thanks

Upvotes: 0

Views: 2114

Answers (1)

Hoch
Hoch

Reputation: 518

Checking the documentation, https://angular.io/api/common/http/HttpErrorResponse

error.message is the server error. try to console.log(error) to see the whole return, or use debugger; too. But, the response from server is error.error, in your case.

Tip: You can use the interceptor to catch your errors.
https://www.tektutorialshub.com/angular/angular-http-error-handling/

Upvotes: 1

Related Questions