How to handle net::ERR_CONNECTION_REFUSED in Angular2

后端 未结 3 516
臣服心动
臣服心动 2021-02-07 01:30

error-handling shows how to handle errors as follows:

private handleError (error: Response | any) {
  // In a real world app, we might use a remote logging infra         


        
相关标签:
3条回答
  • 2021-02-07 02:10
    //First inject the router in the constructor
    
    
    private handleError (error: Response | any) {
    //Your other codes    
    
    if (error.status == 0){ //or whatever condition you like to put
    this.router.navigate(['/error']);
    }
    }
    
    0 讨论(0)
  • 2021-02-07 02:11

    It's impossible distinguish both ERR_CONNECTION_TIMED_OUT (the one someone had mentioned above) and ERR_CONNECTION_REFUSED, because HttpErrorResponse class doesn't differentiate them. So you have to use status 0 to handle all the generic errors. According to list of HTTP status codes https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

    If you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software.

    It means 0 is a non-standard response.

    Angular is a Javascript Framework; hence you should refer to XMLHttpRequest status codes to find out what 0 means. The Mozilla page says..

    Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors.

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status

    So, ERR_CONNECTION_REFUSED means the connection is not established (request is not completed), and therefore, the status code is 0. In that case it's safe to say "Unable to Connect to the Server". throwError is a RxJs function that emit error message, which you can read through Subscribe() method.

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
          catchError((errorResponse: HttpErrorResponse) => {
           if (errorObj instanceof HttpErrorResponse) {
            if (errorObj.status === 0) {
              return throwError('Unable to Connect to the Server');
            }
           }
          })
        );
      }
    
    0 讨论(0)
  • 2021-02-07 02:31

    This happens when you try to reach an insecure https site.

    A solution is : first connect to the insecure site with your browser, a warning page will display. Click on "advance parameter" and accept this site as secure. Second you can reach this destination with your Angular code.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题