KTT
KTT

Reputation: 321

I can't get an error response node.js return in angular

I want to get an error response message sent by node with angular, but I can not do that.

Node.js:

res.status(401).send({ "ERROR": "001", "message": "this is error" });

Angular:

public get(body) {
    return this.httpClient.post(`${this.API_URL}~`, body).catch(this.handleError);;
  }

  private handleError(error: any) {
    console.log(error);
    return Observable.throw(error);
  }

console in chorme

Http failure response for http://localhost:8000/~: 401 Unauthorized

response in chome

{"ERROR": "001", "message": "this is error"}

Although I can confirm it on the chrome network , I can not use the error message in angular because the output in console.log is 'Http failure response for http: // localhost: 8000 / ~: 401 Unauthorized'

Upvotes: 1

Views: 726

Answers (1)

wentjun
wentjun

Reputation: 42526

When it comes to error handling in Angular, the best practice would be to handle it through pipeable operations using RxJS operators.

You can do so by using the catchError operator.

import { catchError } from 'rxjs/operators';
.
.

public get(body) {
  return this.httpClient.post(`${this.API_URL}~`, body)
    .pipe(
      map(...),
      catchError(error => {
        // to get error response object
        console.log(error);
        // handle the rest of the error here
      })
    );
}

To access the error code, you can use error.status.

To access the error message, you can use error.message.

Upvotes: 3

Related Questions