0

I have a service, which sends a http get request to a uri. Here is my code:

@Injectable()
export class InstagramService {
    constructor( private _http:Http ){            

    }
    getGallery(username: string) : Observable<dataSet> { 

      return  this._http.get("http://www.instagram.com/"+username+"/media/").map(res =>  res.json(),  
                                                                                 (err)=>console.log("Error is:"+err) );

    }
}

And sometimes i get a 404 exception, i need to handle this exception, and does not let it appear in my console. I thought (err)=>console.log("Error is:"+err) could be helpful, but the error is still in the console.

I have seen this, but is there an easier way to handle this exception without costume exceptionhandler?

Jeff
  • 7,767
  • 28
  • 85
  • 138

1 Answers1

0

You could also leverage the catch operator:

@Injectable()
export class InstagramService {
  constructor( private _http:Http ){            

  }
  getGallery(username: string) : Observable<dataSet> { 

    return  this._http.get("http://www.instagram.com/"+username+"/media/")
      .map(res =>  res.json())  
      .catch(err => { // <-----
        // do something when error occurs
      });
  }
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • 2
    there is an error: **[ts] Property 'catch' does not exist on type 'Observable'.** – Jeff Aug 12 '16 at 11:21
  • yes, you need to include it explicitly: `import 'rxjs/add/operator/catch';`. See this question: http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276 – Thierry Templier Aug 12 '16 at 11:32
  • Sorry,in the **catch** i need to return something for the caller method which shows that 404 happend. I expected that **null** can help me, but it seems that i should return a **Observable**. and the **dataSet** is an interface, so can i u complete your answer with a return value? – Jeff Aug 12 '16 at 12:08