Pardeep Jain
Pardeep Jain

Reputation: 86730

Error Handling Mechanism while Http Request (REST API) angular2

I am making some REST call (using HTTP request) in angular2.As depend on condition requests are of type GET,POST,PUT,DELETE. Everything works fine for me i am using the below method to make request using seprate service file and class (component class) file.

* service.ts

PostRequest(url,data){
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');

this.requestoptions = new RequestOptions({
    method: RequestMethod.Post,
    url: url,
    body: JSON.stringify(data),
    headers: this.headers
})

return this.http.request(new Request(this.requestoptions))
    .map((res: Response) => {
        if (res) {
            if(res.status == 201){ 
                return [{ status: res.status, json: res.json }]    
            }
            else if(res.status != 201){ 
                return [{ status: res.status, json: null }]
            }
        }
        // i want to handle error here but how i don't know
    }); 
}
this.base_path_service.PostRequest(url_postSection, data)
.subscribe(res=> {
   if (res[0].status == 201) {  //some stuff here..... }
});

Now come to question, my Question is

Upvotes: 1

Views: 1639

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

You can leverage the catch operator to handle errors:

return this.http.request(new Request(this.requestoptions))
    .map((res: Response) => {
        if (res) {
            if(res.status == 201){ 
                return [{ status: res.status, json: res.json }]    
            }
            else if(res.status != 201){ 
                return [{ status: res.status, json: null }]
            }
        }
    }).catch(error) => {
      // Do something
      // Observable.throw(new Error('some error');
    }); 
}

In fact when an error occurs, the registered callback un the map operator won't be called.

Upvotes: 3

Related Questions