5

What is the best practice to call with angular2 REST SERVICE and catch any global exceptions to handle errors and show custom messages.

Has anyone experiences with that?

Michael Burger
  • 643
  • 1
  • 9
  • 17
  • 2
    You might look for http://stackoverflow.com/questions/37609725/how-to-inject-my-service-to-exceptionhandler or http://stackoverflow.com/questions/35274523/handling-angular-2-http-errors-centrally – Günter Zöchbauer Jun 10 '16 at 08:36
  • I'm a bit late to the game on this one but Thierry Templier has a pretty good answer on just extending the http class for Angular2. http://stackoverflow.com/a/37744126/2106702 – Brady Liles Oct 31 '16 at 02:30
  • https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client – Peter Munnings Nov 10 '16 at 06:10

2 Answers2

11

The best practice i have found so far is to firstly create global service and create your method related to http there. i.e for Get, Put,Post ,Delete request etc. than via using these methods call your API service request and catch there errors using catch block and display message as you want for example :-

Global_Service.ts

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

@Injecable()
export class GlobalService {
    public headers: Headers;
    public requestoptions: RequestOptions;
    public res: Response;

    constructor(public http: Http) { }

    public PostRequest(url: string, data: any): any {

        this.headers = new Headers();
        this.headers.append("Content-type", "application/json");
        this.headers.append("Authorization", 'Bearer ' + key );

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                    return [{ status: res.status, json: res }]
            })
            .catch((error: any) => {     //catch Errors here using catch block
                if (error.status === 500) {
                    // Display your message error here
                }
                else if (error.status === 400) {
                    // Display your message error here
                }
            });
    }

    public GetRequest(url: string, data: any): any { ... }

    public PutRequest(url: string, data: any): any { ... }

    public DeleteRequest(url: string, data: any): any { ... }
 }

better to provide this service as dependency at the time of bootstraping your app like this :-

bootstrap (APP, [GlobalService, .....])

than whereever you want to call the request call the request using these globalservice methods like this :-

demo.ts

export class Demo {
     ...
    constructor(public GlobalService: GlobalService) { }

    getMethodFunction(){
       this.GlobalService.PostRequest(url, data)
        .subscribe(res => {console.log(res),
                   err => {console.log(err)}
             });
    }

see also

Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
2

The best solution is to wrap the Http service with your own service. For example you create a service called YourHttp. YourHttp should implement the same interface as Http.

Inject Http into YourHttp and have each method, get, post, put.. etc call the http method and then catch and handle any errors.

Now in your components inject YourHttp. For extra credit, configure DI to inject YourHttp when your components are annotated to have Http injected.

Update

Now that there is HttpClient, it is best to use an interceptor.

Martin
  • 15,820
  • 4
  • 47
  • 56