Search code examples
angularrestinstagram-api

RXJS - Handling 404 error on Instagram API


I'm using the Instagram API that doesn't use OAuth https://www.instagram.com/explore/tags/{tag}?__a=1

It works like a charm, I get the JSON and I am able to manipulate it the way I need, however, I'm getting an error when the tag doesn't exist. I get the 404 error (as HTML instead of JSON) and I'm not able to read the header to get ok or status. I looks like the error prevents the script of getting the response.

I am trying to get the response type to either return the data or null (in case the hashtag doesn't exist).

Can somebody help me?

getPictures(tag: string) {
    const BASE_URL = 'https://www.instagram.com/explore/tags/' + tag + '?__a=1';
    return this.http.get(BASE_URL)
      .pipe(
        map(
          (response: Response) => {
            console.log(response.headers.values()[0]);
            const data = response.json();
            return data.graphql.hashtag.edge_hashtag_to_media.edges;
          }
        )
      );
  }

Solution

  • i think you should use catchError from RXJS like this:

    getPictures(tag: string) {
    const BASE_URL = 'https://www.instagram.com/explore/tags/' + tag + '?__a=1';
    return this.http.get(BASE_URL)
      .pipe(
        catchError((err) => {
          if(err.status === 404)
             //DO SOMETHING
          } 
          return EMPTY;
        ),
        map(
          (response: Response) => {
            console.log(response.headers.values()[0]);
            const data = response.json();
            return data.graphql.hashtag.edge_hashtag_to_media.edges;
          }
        )
      );
    

    }


    EDIT
    Concerning the "EMPTY", it's from RXJS and it allow to return an empty observables to be consumed by the "map" function ;)

    import { EMPTY } from "rxjs";