gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:50:10 26 4
gpt4 key购买 nike

对我api的所有调用都是通过我使用“GET,POST,PUT,DELETE,PATCH”方法创建的服务进行的。如果这些 call 中的任何一个失败,我都希望在警报中显示该错误,并且如果错误状态为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
}

希望这可以帮助

关于javascript - 以相同方式处理所有http错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com