-2

I have many services in my app and many http request. I want to show alert to user that there was problem with api connection in the alert box, but i dont want to edit each http funcion in each service. Can I do this in one place?

Pawel
  • 147
  • 1
  • 1
  • 12
  • 1
    [With an interceptor](https://angular.io/guide/http#advanced-usage) if you're using `HttpClient`, by subclassing or wrapping `Http` and injecting your own version if you're not. See e.g. https://stackoverflow.com/questions/43104627/centralized-handling-for-http-errors-in-angular-4, https://stackoverflow.com/questions/44929046/generic-http-error-handling-in-angular for examples of the latter. – jonrsharpe Jan 19 '18 at 08:09

1 Answers1

2

Interceptors are the way to go. But you will have to use the new HttpClient instead of the old, soon-to-be deprecated Http.

Something like this:

@Injectable()
export class ErrorHandlerService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
      .handle(req)
      .catch(err => {
        console.log('HTTP error occured');
        return Observable.throw(err);
      });
  }

}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • I've injected it before other services, but your interceptor does not log error. it logs only: https://imgur.com/a/fOvIp – Pawel Jan 19 '18 at 08:42
  • I don't have access to images (corporate proxy), and it's usually not recommended to upload your errors as images on SOF. Could you show the trace directly to me please ? And did you inject your interceptor as the tutorial asks you to ? –  Jan 19 '18 at 08:46
  • i've figuret it out already., thank you. could you show me example how to listen to it for example in some alert component? – Pawel Jan 19 '18 at 09:01
  • Well, you could use the **[Snackbar from Angular material](https://material.angular.io/components/snack-bar/overview)**, this is what I do and it's very easy to use (all the tutorials are in this site) ! –  Jan 19 '18 at 09:13