1

I have a service that will return http query, my caller will by default receive the result and assign it to a News[] object.

 this.service.getNews(url).subscribe((res) => this.news = res);

now I want to throw a custom error if any error occured:

getNews(url:string): Observable<News[]> {
  return this.http.get<News[]>(url).catch(err => {
  throw new Error("My Custom Error");
});

But I got a compling error that "cannot assign the {} to a Observable < News[] >" because the error is not a type of News[].

So how can I modify the code to return an error without changing the returning type Observable < News[] >?

3
  • how about catch the error when subscribe executes? Commented Aug 29, 2018 at 17:50
  • what is the rxjs version Commented Aug 29, 2018 at 17:50
  • Observable.throw or import _throw: _throw(new Error(...)) Commented Aug 29, 2018 at 21:18

1 Answer 1

3

Instead of throwing your error, try returning an observable of it using Observable.throw.

The docs specifically remind to return an observable from the catch operator.

Sign up to request clarification or add additional context in comments.

1 Comment

URL needs to be updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.