简体   繁体   English

Angular 7 http 错误处理无法正常工作

[英]Angular 7 http error handling not working properly

I am trying to handle 422 error handling on my HTTP request.我正在尝试处理我的 HTTP 请求的 422 错误处理。 But somehow the error block doesn't run in the service using catchError operator.但是不知何故,错误块不会在使用 catchError 运算符的服务中运行。 If there is no error the code is just working fine.如果没有错误,代码就可以正常工作。 I want to display error message on my page.我想在我的页面上显示错误消息。 But angular is only throwing error in console and not running the error block.但是 angular 只是在控制台中抛出错误而没有运行错误块。 Here is my http error response:这是我的 http 错误响应:

在此处输入图像描述

And here is the error I am getting only in console.这是我只在控制台中遇到的错误。

在此处输入图像描述

I want to display error message on my page.我想在我的页面上显示错误消息。 Here is my HTTP request.这是我的 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));
        })
      );
  }

And here is my method to subscribe to the it.这是我订阅它的方法。

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;
      });

Probably you have an interceptor that catches the error.可能您有一个捕获错误的拦截器。 If you need to handle errors in the interceptor, you may consider throwing them after your handling logic.如果你需要在拦截器中处理错误,你可以考虑在你的处理逻辑之后抛出它们。

Try removing this code from your Http call: 尝试从Http调用中删除此代码:

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

And handle your error inside the error block of your subscribe method. 并在subscribe方法的错误块中处理您的错误。

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;
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM