在 aurelia (typeScript) 中以通用方式处理 403 错误
Handling 403 error in generic way in aurelia (typeScript)
有没有办法以通用方式处理从服务器发送的 403 响应,而无需在 catch 块中单独处理它们中的每一个?`
//当前代码
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 文件得到 class 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;
}
}
有没有办法以通用方式处理从服务器发送的 403 响应,而无需在 catch 块中单独处理它们中的每一个?`
//当前代码
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 文件得到 class 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;
}
}