0

All over the tutorial for Angular2 I see that exceptions are being caught right where the call is, e.g.:

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

While this might be good for the tutorial, this does not sound sustainable for me. I would like to have some global handler that will e.g. overlay/popup some message to a user and log the error to console + override it when I need some special handling (e.g. if I read the json error and find that I can handle it in a more user-friendly way than just a popup for one of the components), without the need to override it everywhere like the example from Angular2 suggests.

Is it possible to achieve?

P.S. A C# analogue would be some global.asax Application_Error + TaskScheduler.UnobservedTaskException error handling for example.

2 Answers 2

3

There's no way you can make all Observables do some globally predefined behavior.

Since you probably want to handle mostly request from http in some uniform way you can replace the default http service with your own that extends methods such as get() or post() and always append catch() or retryWhen() operators. See:

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

Comments

2

The thing is, I don't think the http is throwing an exception, not in the usual sense. It is calling the catch delegate when a HTTP error code is received.

From reading around you can catch globally thrown errors like in C# using the ErrorHandler but in your promise you will still have to throw it like in this example

Comments

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.