【问题标题】:Angular 7 http error handling not working properlyAngular 7 http错误处理无法正常工作
【发布时间】:2019-10-17 15:14:47
【问题描述】:

我正在尝试对我的 HTTP 请求进行 422 错误处理。但不知何故,错误块没有在使用 catchError 运算符的服务中运行。如果没有错误,代码就可以正常工作。我想在我的页面上显示错误消息。但是角度只是在控制台中抛出错误而不运行错误块。 这是我的 http 错误响应:

这是我只在控制台中遇到的错误。

我想在我的页面上显示错误消息。这是我的 HTTP 请求。

 renderPlugin(id): Observable<any> {
 return this.http
      .get(`${environment.kbUrl}/${id}?_as_json=1&_nbp=1`, {
        responseType: "text",
        observe: "response"
      })
      .pipe(
        catchError((res: HttpErrorResponse) => {
          console.log(JSON.stringify(res));
          this.toastr.error("error", JSON.stringify(res));
          return throwError(JSON.stringify(res));
        })
      );
  }

这是我订阅它的方法。

this.pluginsService.renderPlugin(this.currentId).subscribe(res =>{
    this.currentString = res.body;
    this.plugin = this.currentString.data.content;
    console.log(this.plugin);
      },
      err =>{
        this.plugin = err;
      });

【问题讨论】:

  • 为什么需要使用 -> 观察:“响应”?因为这是唯一可以给出问题的东西,其余的代码是“好的”
  • 尝试从 res 中删除类型以查看它是否有效,以及它是否是不同类型的错误
  • 我已经尝试了这两个建议,但仍然无法显示任何错误。甚至没有控制台记录错误。
  • 您的 http 状态码是否正确显示为 422?您可以在开发者工具中查看。
  • 是的,状态码是 422。我已经在开发者工具中检查了。

标签: angular typescript rxjs


【解决方案1】:

可能你有一个拦截器来捕获错误。如果你需要在拦截器中处理错误,你可以考虑在你的处理逻辑之后抛出它们。

【讨论】:

    【解决方案2】:

    尝试从您的 Http 调用中删除此代码:

      .pipe(
        catchError((res: HttpErrorResponse) => {
          console.log(JSON.stringify(res));
          this.toastr.error("error", JSON.stringify(res));
          return throwError(JSON.stringify(res));
        })
      )
    

    并在订阅方法的错误块中处理您的错误。

    this.pluginsService.renderPlugin(this.currentId).subscribe(
        res => {
            this.currentString = res.body;
            this.plugin = this.currentString.data.content;
            console.log(this.plugin);
        },
        err => {
           // Handle the error here
           // like displaying toast using the error message received from server
           this.plugin = err;
        }
    );
    

    【讨论】:

    • 仍然无法正常工作,我不明白为什么它甚至 console.log(err) 都无法正常工作。
    • 我创建了一个 stackblitz:stackblitz.com/edit/angular-wgl4km 它使用的代码类型与您的类似,并且可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2020-03-01
    • 2019-05-03
    • 2018-12-05
    • 2020-05-01
    相关资源
    最近更新 更多