gpt4 book ai didi

typescript - 在 aurelia (typeScript) 中以通用方式处理 403 错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:33 25 4
gpt4 key购买 nike

有没有办法以通用方式处理从服务器发送的 403 响应,而无需在 catch block 中单独处理它们中的每一个?`

//当前代码

  searchCustomer(customerName: string): any {
if (customerName != "") {
let url = 'clinics/customers/lookup/name/' + customerName;
let headers = new Headers();
headers.append('accept', 'application/vnd.vetserve.customerlookup.v1.hal+json');
return this.http.fetch(url, { method: 'GET', headers: headers })
.then(response => response.json())
.catch(error => {
if(error.status==403){
this._messageService.showMessage('No permission', MessageService.type.error, error);
}
console.log(error);
}
);
}
}`

最佳答案

感谢@thebluefox 建议中断,这是最好的方法,也是我需要的,api-client.ts 文件有 ApiClient 类,我们可以像下面这样修改它.withInterceptor 中的 response(response) 条件捕获错误

  export class ApiClient {
http:HttpClient = null;

constructor(aurelia:Aurelia, auth:AuthenticationService) {
let httpClient = new HttpClient();
httpClient.configure(httpConfig => {
httpConfig
.withDefaults({
headers: {
'Accept': 'application/json'
}
})
.withInterceptor({
request(request) {
if (!auth.isAuthenticated()) {
aurelia.setRoot('authentication');
};
request.headers.append('Authorization', 'bearer ' + auth.accessToken);

return request;
}
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response

}
})
.useStandardConfiguration()
.withBaseUrl(config.api_endpoint);
});
this.http = httpClient;
}
}

关于typescript - 在 aurelia (typeScript) 中以通用方式处理 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061759/

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