Angular2 HTTP - How to understand that the backend server is down

后端 未结 3 1465
我在风中等你
我在风中等你 2021-02-19 07:55

I am developing a front end which consumes JSON services provided by a server.

I happily use HTTP of Angular2 and I can catch errors via .catch() operator.

3条回答
  •  迷失自我
    2021-02-19 08:50

    Well i have faced something similar before. I was trying to make a logging Service and a Error handling which tells the user if error happened with some requests to the server or if the whole server is down.

    I used HTTP Interceptor to catch the responses here is the code:

    export class HttpErrorHandlingInterceptor implements HttpInterceptor {
       constructor(private logService: LogService,
                   private layoutStateService: LayoutStateService){}
       intercept(
          req: HttpRequest,
          next: HttpHandler
       ): Observable> {
         if (req.url) {
             return next.handle(req).pipe(
                    map((event: HttpEvent) => {
                       if (event instanceof HttpResponse) {
                            return event;
                       }
                    }),catchError(err => {
                        if(!err.status){
                           this.layoutStateService.dispatchServerDown();
                        }else{
                           this.layoutStateService.dispatchAddServerError(err);
                           this.logService.logError(err);
                        }
    
                   throw err;
                 })
            );
        }
      }
    }
    

    Now you can specify what should happen when Server is down according to your application. Hope that helps.

提交回复
热议问题