在奥雷利亚中以通用方式处理403错误(typeScript)

x33g5p2x  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(82)

是否有任何方法可以处理从服务器发送的403响应,而不是在catch块中单独处理它们?

searchCustomer(customerName: string): any {
            if (customerName != "") {
                let url = '{url}';
                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);
                    }
                        );
            }
        }`
os8fio9y

os8fio9y1#

感谢@ thebulefox建议interseptions,这是最好的方法和我所需要的,api-client.ts文件得到类ApiClient我们可以修改,如下面的响应(响应)条件。

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;
      }
    }

相关问题