2

I'm wrinting a pice of Angular2 code that interacts with a server which returns a json with http error codes such as 404 or 401. I can't find a way to read the json out of the error response. I can't use .map() since there is no data on normal response.

return new Promise((resolve, reject: Response) => {
      this.http.request(new Request(requestoptions))
          .subscribe(
          data => {resolve()},
          error => { error.json() } //<-- No json()
          )
       };

How handle this?

4
  • check this on how to handle errors while Http Call. Commented Dec 15, 2016 at 21:38
  • try error => console.log(error), The error object response may not be a json object. What's the api send code look like? Commented Dec 15, 2016 at 22:50
  • The error code contains a json object ( i see this in the http response in the browser) Commented Dec 16, 2016 at 0:35
  • @ApriOri I'm facing your same problem: did you figure out how to solve? Commented May 31, 2017 at 12:53

1 Answer 1

1

I solved my issue by trying to parse only http codes that contain response. This sample code may help others:

return new Promise((resolve, reject) => {
  this.httpProvider.login(url, credentials)
    .map(res => {
      //avoid parsing the response from the server for some requests since it's not a valid json
      if (res.status >= 400 && res.status < 500) {
        return res.json();
      }
      else return res;
    })
    .subscribe(
      data => {
      },
      error => {
        switch (error.status) {
          case 400:
          case 401:
            let erromsg: string = this.parseServerError(error);
            reject(erromsg);
            break;
          case 404:
          case 500:
            reject("Server error");
            break;

          default:
            reject("Network Error");
        }
      }
    );
});




parseServerError(error): string {
  try {
    let message = error.json().message[0].description;
    return message;
  } catch (e) {
    return "Undefined error";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.