typescriptgenericserror-handlingaureliahttp-status-code-403

Handling 403 error in generic way in aurelia (typeScript)


Is there any way of handling 403 responses sending from server in generic way without handling each of them separately inside catch block?`

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

Solution

  • Thanks @thebluefox for suggesting the interseptions, This is the best method and what i needed, api-client.ts file got class ApiClient we can modify that like below response(response) condition in .withInterceptor catchs the error

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