0

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

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

error.error.message is actually what OP is looking for

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.