7

I am trying to make an ajax call with Http service, which is working fine.

Now I would like to handle failure cases. Example if we get 404 or any other errors.

I am using the following code.

import {Component,Inject} from '@angular/core';
import {Http, Response,HTTP_PROVIDERS} from '@angular/http';
import {DoService} from './service';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';

@Component({
    selector: 'comp-one',
    template: `<h2>My First Angular 2 App</h2>{{data}}
        <input type="button" (click)="doSomething()" value="Do Http"/>`
})

export class ComponentOne { 
    constructor(public _http:Http){
    console.log("It is from ComponentOne constructor..");
        this._http = _http;
    }
    data:Object;
    doSomething(){
        console.log("It is from doSomething ComponentOne");
        let temp:any = this._http.get('people.json')//people.json is not exist, intendedly maing any error
     .map(res => res.json())
        .catch((err:any)=>{ console.log("Something is wrong..")});// If i keep this line i am getting errors like "Argument of type '(err:any) => void' is not assignable to parameter of type '(err: any, caught: Observable<any>) => Observable<{}>"
        temp.subscribe(
        (res:any)=> {this.data = res._body; console.log(res)},
        (error:any)=>{ console.log("It isf from error..")},//It is not even getting called this block
        () => console.log('thire,,,ddjfladjfljasdlfj'));//In one of the forum they suggested to use this 3rd perameter, this is also not working for me.

  } 

}
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
ayyappa maddi
  • 854
  • 3
  • 10
  • 18

2 Answers2

8

You need to return observable from the catch block as this is the signature of this. So try

return Observable.throw(new Error(error.status));

Here is the snippet

import {Observable} from 'rxjs/Rx';
...

return this.http.request(new Request(this.requestoptions))
    .map((res: Response) => {
        if (res) {
            if (res.status === 201) {
                return [{ status: res.status, json: res }]
            }
            else if (res.status === 200) {
                return [{ status: res.status, json: res }]
            }
        }
    }).catch((error: any) => {
        if (error.status === 500) {
            return Observable.throw(new Error(error.status));
        }
        else if (error.status === 400) {
            return Observable.throw(new Error(error.status));
        }
        else if (error.status === 409) {
            return Observable.throw(new Error(error.status));
        }
        else if (error.status === 406) {
            return Observable.throw(new Error(error.status));
        }
    });
}

see also

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • 1
    We should ideally have a list of statuses we want to handle in an array and then compare with that to have a simple Ob.throw(). For error 500, the user cannot do anything since something wrong on server, but for 401 they need to check their credential and similar – NitinSingh Jun 11 '17 at 10:58
5

You can try to return Observable object from catch callback like this:

doSomething(){
  console.log("It is from doSomething ComponentOne");
  let temp:any = this._http.get('people.json')
     .map(res => res.json())
     .catch((err:any) =>{ 
        console.log("Something is wrong..");
        return Observable.of(undefined); <== this line 
     });

  temp.subscribe(
     (res:any)=> {this.data = res._body; console.log(res)},
     (error:any)=>{ console.log("It isf from error..")},
     () => console.log('thire,,,ddjfladjfljasdlfj'));
}
yurzui
  • 205,937
  • 32
  • 433
  • 399