Global Error Handler for all Http calls with global Toast message

We are trying to create a global error handler for all HTTP calls using a Toast message.

First of all we created a custom global HttpService like this

@Injectable()
export class HttpService extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    get(url: string, options?: RequestOptionsArgs): Observable<any> {
        //this.requestInterceptor();
        return super.get(url, options)
            .catch(this.onCatch)
            .do((res: Response) => {

            }, (error: any) => {

            })
            .finally(() => {

            });
    }

    private onCatch(error: any, caught: Observable<any>): Observable<any> {
        console.log('onCatch: ', error, caught);

        return Observable.throw(error);
    }
}

After this we have to register the provider in app.module.ts

  providers: [
        {
          provide: HttpService,
          useFactory: (backend: XHRBackend, options: RequestOptions) => {
            return new HttpService(backend, options);
          },
          deps: [XHRBackend, RequestOptions, Platform]
        }
  ]

now we can create for example a UserService which is injecting HttpService and makes a http call using custom http provider to get current user, like this:

@Injectable()
export class UserService {

    constructor(private httpService: HttpService) {}

    current() {

        return this.httpService.get('/api/v1/users/current')
                        .map(res => res.json());
    }
}

As you can see, all this should work fine. In HttpService we catch Errors and call onCatch method where we would like for example check if response is 401 Unauthorized, if so in this point for all calls we would like show a ionic2 Toast with an global message error. But our first problem here is, how can we inject ToastController in the constructor, if we do this we have also to declare it in providers in app.module.ts, which we could do but is this the right solution we are trying to do?

So ionic team in your idea/opintion. How should we handle a gloabal http error handler which shows gloabl toast messages?

In the custom HttpSerive provider we do also other things like add some headers and do some proxy rules.

I think the answer is: you can’t

But using Observable you could subscribe to your service from your app.compoment.ts (for example) and from there, when an event occurs, triggering Toast

1 Like

That’s how I would do it. Inspiration here: https://blog.sstorie.com/adapting-ben-nadels-apigateway-to-pure-typescript/

The code is written before the introduction of NgModule, but should easy to adapt.