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



所有对我的 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));
  }
}
您还可以

在服务中创建catch()方法,并将其分配给http调用的 catch 处理程序。每当 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
}

希望这有帮助

相关内容

  • 没有找到相关文章

最新更新