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?
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
catch is not working for http.get Angular2.
Hope this may help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With