简体   繁体   中英

Handle error when server does not respond

My application is build using Angular 2. A typical pattern I use is seen below. If there is a server error I do a number of things depending on the needs. In the below example I used a comment to indicate a redirect to an error page.

However occasionally something goes wrong and the server does not respond causing the front end to remain in a state of pending with the spinner spinning. I want to know how this kind of situation is dealt with. Is there a common practice for this? Is there a way to redirect at some point in a elegant manner? I feel like I could add a timeout to trigger at a certain time but that really seems like a hack.

private getSites() {
  this.spinner.show();
  this.sitesService.getSites(1)
    .subscribe(
      _data => {
        this.sites = _data;
        this.spinner.hide();
        this.loading = false;
      },
      _error => {
        // Redirect to < something went wrong >
        this.spinner.hide();
      }
    );

}

Based on the responses I was able to learn various ways to deal with this situation. The one I liked best was using timeout operator. Thanks everyone.

private getSites() {
  this.spinner.show();
  this.sitesService.getSites(1)
    .timeout(6000)
    .subscribe(
      _data => {
        this.sites = _data;
        this.spinner.hide();
        this.loading = false;
      },
      _error => {
        // Redirect to < something went wrong >
        this.spinner.hide();
      }
    );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM