Ionic 2: Handle errors from http


#1

On Ionic 1.x, i have create a helper to handle the errors alerts from request in http. But now im the version 2.x, i’m a little confused on how can i handle this, calling multiple functions for feed back. Like a button with “Try Again” triggering the specific function used.

So, how do you guys handle this?


#2

I replace Http for my service and redefined all http method, and implements my own methods to catch http.
Methods like onCatch to handler errors.
Methods like requestInterceptor and responseInterceptor to show/hide spinner

import { Injectable, Inject, forwardRef } from '@angular/core';
import {
    Http,
    RequestOptions,
    RequestOptionsArgs,
    Response,
    Headers,
    Request
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class HttpService {
    constructor(
        private http: Http,
    ) {
       
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.http.request(url, options);
    }

   
    private subscribeCommon(subscribe: Observable<Response>) {
        return subscribe
            .catch(err => this.onCatch(err))
            .do((res: Response) => {
                this.onSubscribeSuccess(res);
            }, (error: any) => {
                this.onSubscribeError(error);
            })
            .finally(() => {
                this.onFinally();
            });
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        this.requestInterceptor();
        return this.subscribeCommon(this.http.get(this.getFullUrl(url), this.requestOptions(options)));
    }

   

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
        this.requestInterceptor();
        return this.subscribeCommon(this.http.post(this.getFullUrl(url), body, this.requestOptions(options)));

    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
        this.requestInterceptor();
        return this.subscribeCommon(this.http.put(this.getFullUrl(url), body, this.requestOptions(options)));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<any> {
        this.requestInterceptor();
        return this.subscribeCommon(this.http.delete(this.getFullUrl(url), options);
    }


    private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
        return options;
    }

    private getFullUrl(url: string): string {
        return url;
    }

    private requestInterceptor(): void {
        this.loadingService.showSpinner();
    }

    private responseInterceptor(): void {
        this.loadingService.hideSpinner();
    }

    private onCatch(error: any): Observable<any> {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            this.parseError(body.code);
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Observable.throw(errMsg);
    }

    private onSubscribeSuccess(res: Response): void { }

    private onSubscribeError(error: any): void {
        /*this.toastService.showMessage({ message: error, duration: 3000 });*/
    }

    private onFinally(): void {
        this.responseInterceptor();
    }

    private parseError(code: any) {
        switch (code) {
            case 401:
               this.logout()
                break;
            default:
                break;
        }
    }

}

#3

i’m using promisses on the services for now.
But on Ionic 1 i usually pass a function to the handle error of the request, like a “Try Again” button on the alert, and have created a helper of alerts to all request status. But i tried this on Ionic 2, and just don’t work.
I know that this is because the away of Typescript, and the Object Oriented way of it, like Java.
Is like the function is detroyed on the execution of the code, you know? I can’t explain because i’m using Ionic 2 directly, and not studied Typescript before using it.