1

How would you catch the error in that case:

   getStuff(): Observable<Stuff[]> {

    return this.http.get(url)
      .map((res: Response) => {
        return res.json()
        .map(item => {
          return {
            id: item.id
            name: item.code
          };
      });
    });

  }

I tried to put .catch() but saying that return type is not matching Supplied parameters do not match any signature of call target.

getStuff(): Observable<Stuff[]> {

    return this.http.get(url)
      .map((res: Response) => {
        return res.json()
        .map(item => {
          return {
            id: item.id
            name: item.code
          };
      });
    })
    .catch();

  }

with .catch((err) => console.error(err)); getting Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<any>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.

Sergino
  • 10,128
  • 30
  • 98
  • 159
  • try `.catch((err) => console.error(err));` – Viet May 19 '17 at 04:23
  • @Jerry06 with this one `Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'` – Sergino May 19 '17 at 04:25
  • The `.catch()` as in `Observable.catch()` is only valid after the initial `.map()`. So `.get().map().catch()` in the observable chain. Yours is in the wrong place. – Neil Lunn May 19 '17 at 04:27
  • @NeilLunn I do not think so that it is in the wrong place, it is exactly in the chain `.get().map().catch()` – Sergino May 19 '17 at 04:41

1 Answers1

1

You can use with Observable.throw

function handleError(error: any) {

  let errorMsg = error.message || `Yikes! There was was a problem `;
  console.error(errorMsg);

  // throw an application level error
  return Observable.throw(errorMsg);
}

And using

 .catch(handleError);
Viet
  • 3,349
  • 1
  • 16
  • 35
  • this working, but how would you do something like `.catch(throw new MyError())` instead of declaring any additional functions? – Sergino May 19 '17 at 04:44
  • 1
    try `.catch(errorMsg => Observable.throw(errorMsg))` – Viet May 19 '17 at 04:50