Angular 2, POST response map error?

My following code works correctly when I take a good response from server

let response = this.http.post(url,sendData).map(res =>res.json());
return response;

but, as soon as I get a non-JSON response from server, the whole app starts breaking down.

Assuming that .json() gives this error i try/catch.

let response:any = this.http.post(url,sendData);
return response.map((resp)=>{      
      try{
        resp.json();
      }
      catch(Error){
        return *what to do*;
      }

      return resp.json();
    });

Full Code Reference

 sendToAPI(sendData,param,option?){

    sendData = JSON.stringify(sendData);
    let url = this.link+param;

    let response:any = this.http.post(url,sendData);        
    return response.map((resp)=>{      
      try{
        resp.json();
      }
      catch(Error){
        ** here ** // need to return a response object
      }
      return resp.json();
    });
  }

What could be the possible way out? When due to some reason API gives a non-JSON parsable error. I should give me an object of this following sort to subscribe to:

{
    status: 0,
    data: [],
    message : "non json response by server"
  }

1 answer

  • answered 2018-01-11 20:42 QuietOran

    So one way to do it in your current set up would be something like this:

    let response:any = this.http.post(url,sendData);        
        return response.map((resp)=>{
          let body = {};
          try{
            body = resp.json();
          }
          catch(Error){
            body = {
                status: 0,
                data: [],
                message : "non json response by server"
            };
          }
          return body;
        });