以相同的方式处理所有http错误

时间:2017-04-01 15:05:18

标签: javascript angular typescript error-handling ionic2

所有对我的api的调用都是通过我使用" GET,POST,PUT,DELETE,PATCH"创建的服务完成的。方法。如果这些调用中的任何一个失败,我想在警报中显示错误,如果错误状态为401,则将用户重定向到登录。如何创建通用错误处理程序?

api.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import lodash from 'lodash';

@Injectable()
export class ApiService {

  url: string = 'https://leetags-api.herokuapp.com';
  options: RequestOptions = new RequestOptions({
    withCredentials: true
  });

  constructor(private http: Http) {}

  get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
    if (params) {
      const urlSearchParams: URLSearchParams = new URLSearchParams();
      lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
      options.search = !options.search ? urlSearchParams : options.search;
    }

    return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

}

1 个答案:

答案 0 :(得分:0)

您还可以在服务中创建catch()方法,并将其分配给http来电的抓取处理程序。只要api调用失败,就会自动调用.catch块。

您的上述http语句应如下所示(对于GET):

get() {
        return this._http.get(this.getUserUrl)
                .map((response: Response) => response.json())
                .catch(this.myCatchFunction);
    }

myCatchFunction(error: Response){
 //look here for specific codes present in response error and handle accordingly
}

希望这有帮助