【问题标题】:Observable HttpResponseError可观察到的 HttpResponseError
【发布时间】:2020-09-23 13:08:06
【问题描述】:

我正在尝试使用 observable 处理 HttpError 或 HttpErrorResponse 但我所能做的就是处理所需的 HttpResponse 但我还需要避免这种情况

我需要能够在响应出现问题时提醒用户,也许他们可以重试...

this.addService.log()
          .subscribe(event => {
            if (event instanceof HttpResponse) {
              //do something
            } else if ( event instanceof HttpErrorResponse){ 
              console.log(`couldn't httperrorresponse`)
            } else if (event instanceof ErrorEvent){ 
              console.log(`couldn't errorevent`)
            } 
    });
}

我已经尝试将整个东西封装在一个 try catch 中,但它仍然没有抛出错误

【问题讨论】:

  • 您需要在subscribe 的错误回调中编写错误处理程序,因为任何服务器端错误都将由错误回调处理,因此您不会在成功回调中获得任何HttpErrorResponse 实例你上面写的

标签: angular observable httprequest httpresponse http-error


【解决方案1】:

您可以使用 HTTPInterceptor - Interceptor

你会有这样的东西:

@Injectable({
  providedIn: 'root'
})
export class ErrorInterceptorService implements HttpInterceptor {

  constructor(private toastr: ToastrService, private router: Router) { };

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      retry(1), // repeating the request one time on error
      catchError((error) => {
        if (error) {
            // Do what you want with the error
            return throwError(error); // Throw error like it normally does, without the catchError
        }
     }
  }

你可以试试这个tutorial

【讨论】:

    【解决方案2】:

    无需创建服务的最佳方法...只需添加一个逗号并添加一个错误“订阅”我猜但每次出现错误都会触发...所以... 快乐的编码呼吸

    this.addService.log()
              .subscribe(event => {
                if (event instanceof HttpResponse) {
                  //do something
                } else if ( event instanceof HttpErrorResponse){ 
                  console.log(`couldn't httperrorresponse`)
                } else if (event instanceof ErrorEvent){ 
                  console.log(`couldn't errorevent`)
                }}, err=>{
                    console.log(err)
                    JSON.stringify(err)
                });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2019-09-09
      • 2011-06-09
      • 2017-08-08
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      相关资源
      最近更新 更多