How to handle net::ERR_CONNECTION_REFUSED in Angular2

后端 未结 3 526
臣服心动
臣服心动 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条回答
  •  猫巷女王i
    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, next: HttpHandler): Observable> {
        return next.handle(req).pipe(
          catchError((errorResponse: HttpErrorResponse) => {
           if (errorObj instanceof HttpErrorResponse) {
            if (errorObj.status === 0) {
              return throwError('Unable to Connect to the Server');
            }
           }
          })
        );
      }
    

提交回复
热议问题