【问题标题】:how to print only error message in Angular如何在Angular中仅打印错误消息
【发布时间】:2020-07-02 16:50:20
【问题描述】:

我正在尝试找到一种方法,仅打印我的 api 调用错误中的“消息”部分,但不确定如何仅获取该部分,因此如果我能得到任何建议或帮助,我将不胜感激。

So this is what it show me in the network tab when there is error in the api call (pic)

 saveChartClick(err: any) {
    // update the chart data here
    if(!this.isTextChart && !this.isFigure && !this.isGrid){
      this.chartService.updateChart(this.chart).pipe(takeUntil(this.death$)).subscribe((updated) => {
        if(updated) {
          this.chart = updated;
          this.snackbar.open("Chart has been updated.", " ", {duration: 2500});
          this.store.dispatch(updateChart({chart: this.chart}));
        } else {

          this.snackbar.open(err.message, "close ", { duration: 2500 });
        }
      }, err => {
        this.snackbar.open(err.message, "close ", { duration: 2500 });
      })
    }
    else{
      // save the new data here
      this.store.dispatch(saveChartData({ guid: this.chart.guid, data: this.chartData }));
    }
  }

现在它向我显示了这个,这不是我想要显示的,因为它并不能真正说明错误是什么。

Error Message it showing me right now (pic)

This is hard coded but this one example of what I want to display (pic)

错误在后端处理,有时我会收到不同的错误消息,所以我不想硬编码。

【问题讨论】:

  • this.chartService.updateChart 是什么?
  • 我认为最好的方法是控制整个错误对象并通过它来查看最适合您的项目以及您想要显示的项目。如果没有很好的错误消息,那么在 err 上只需使用 IF 并传递您想要的消息
  • 嗨,这是一个 api 调用(刚刚在我的帖子中发布)。在我添加那个调用之前,我们只做了 this.store.dispatch(updateChart({chart: this.chart}));并且它正在工作,它在小吃栏中显示一条错误消息,但是当它成功更新时它没有显示任何内容,所以我认为我应该添加它以显示成功的小吃栏消息。

标签: html angular api types error-handling


【解决方案1】:

在 Angular 的 HttpErrorResponse 对象中,message 属性是这样的。你想要的不是

this.snackbar.open(err.message, "close ", { duration: 2500 });

但是

this.snackbar.open(err.error.message, "close ", { duration: 2500 });

或者,为了安全起见(error 可以为空),

const errorMessage = err.error ? err.error.message : err.message;
this.snackbar.open(errorMessage, "close ", { duration: 2500 });

【讨论】:

  • 啊好吧..不知道为什么 const errorMessage 不起作用(不显示错误消息,只显示 "close" )但 err.error.message 对我有用,所以谢谢你的帮助。真的很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2020-04-25
相关资源
最近更新 更多