0

i have a little problem, i have this code which work when it has to return a status 200 (all is OK)

   httpCallGet(pathToCall: string, varToSend: string ): Observable<any> {
    return this.http.get(this.url + pathToCall + varToSend, {headers : this.headers} )
        .map( res => res.json())
        .catch(this.handleError);
}

But when the URL is wrong and i have a 404 error, my site just crash with a console error.

How can i properly catch this type of error without error on the console and can i retry when error ?

I try .retry(3) but this code don't work and .subscribe don't work with Observable return (i'm not very easy with Observable ^^)

As someone an idea to fix this ?

3
  • if the url is wrong, and you do .retry(3) it will just fail 3 more times. get the right url, make sure calls can successfully be made to the url in your terminal using curl Commented Oct 3, 2017 at 16:01
  • what does your this.handleError do? Commented Oct 3, 2017 at 16:06
  • One of the way is to create default action. But probably you have used another backend. Commented Oct 3, 2017 at 16:06

1 Answer 1

1

Have your service return an observable that either returns the result or throws the error.

 httpCallGet(pathToCall: string, varToSend: string ): Observable<any> {
  return this.http.get(this.url + pathToCall + varToSend, {headers : this.headers} )
    .map( res => res.json())
    .catch(error => Observable.throw('error');
};

Then in your component, handle the error.

getHttpData = () => {
  this.service.httpCallGet('someurl', '')
    .subscribe(
      result => this.handleResult(result),
      error => this.handleError(error)
    )
};

handleResult = (data) => {
  // do stuff with data
};

handleError = (error) => {
  // do stuff with error
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, It works good. I thought i can manage the error directly in the .get call but i can only do it in the subscribe (when the 'real' call begin and end), right?
You need an observable to provide the subscribe method. I suspect you weren't returning one from service.handleError. Can you accept the answer if it helped you?

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.