MMR
MMR

Reputation: 3009

How to catch errors in angular 2?

I ave a server call like below

In success case,

STATUS---200

{error_code: 0, status: "success", results: [,…], message: "Album successfully found."}

In failure case, STATUS---401

 Login credentials are incorrect.

I am handling the code as,

 this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }) 
  }

But here its an error (401-status).So it is not coming to the else case.Can anyone suggest help to handle or catch this error.thanks.

Upvotes: 1

Views: 1477

Answers (3)

Milad
Milad

Reputation: 28592

You can use .catch as well :

this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(response => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        }).catch((err)=>{console.log(err)}); 

Upvotes: 1

eko
eko

Reputation: 40647

Subscribe has an error callback:

 this.http.post(this.serverUrl+'login',loginForm.value,{headers: headers})
        .subscribe(
        (response) => {
            if (response.json().error_code === 0) {
               console.log('success'); 
            } else {
               console.log('fail'); 
            }
        },
        (error)=>{
            console.log(error);
        }
     ) 
  }

Example in docs: https://angular.io/docs/ts/latest/guide/server-communication.html#!#the-herolistcomponent-class

Upvotes: 1

ulubeyn
ulubeyn

Reputation: 3021

Subscribe method takes 3 parameters, first one is invoked when successfull response is received, second one is called when error response is received, and third one is called when it is completed. You should try this one;

this.http.post(yourParameters).subscribe(response => {
     console.log('success');
}, error => {
     console.log('fail')
});

I also recommend you to take a look at angular tutorial and Rxjs Subscribe.

Upvotes: 1

Related Questions