首页 > 解决方案 > 在 Angular 中未收到来自 API 的错误响应

问题描述

我在 Angular 中调用 API 并尝试获取响应正文,但它只是显示error message is [object Object]

我试过只是做console.log(error), error.text(), JSON.parse(error._body).errors, error.error,error.messageerror.json()没有奏效。

这是我的代码,非常感谢一些帮助:

  doImport = (dataObj) => {
    for(let i = 0; i<this.uploadedFilesCount; i++) {
      const filename = this.uploadedFileNames[i];
      this.disableDeployCTA = true;
      const params:string = filename + "/" + this.testStartTime + "/" + this.userNtId + "/" + this.userTeamID + "/" + this.userTeam; 
      var res = '';
      this.httpService.importUML(params).subscribe((response: any) => {        
        this.toastmessage.success('Successfully created test #'+i); 
        this.toastmessage.clear();
      },                              
      (error) => {
        console.log("error message is "+error.message);
        if(error.status == 409) {
          if(res.indexOf("static data")!=-1) {
            this.toastmessage.error(filename + ": That static data exists already!");
          }
          else {
            this.toastmessage.error(filename + ": That test case exists already! Please change test case name.");
          }
        }
        else if(error.status == 400) {
          this.toastmessage.error(filename + ": Incorrectly formatted UML. Please fix and try again.");
        }
      });
    }
    this.resetAxiForm();
    this.disableImport = true; 
  } 

我想得到的错误响应:

在此处输入图像描述

当我执行 console.log(error) 时: 在此处输入图像描述

标签: angularresthttpangular-httpclient

解决方案


这是一个很常见的错误console.log,这里发生的事情是你收到的错误实际上是一个object,你用那个+标志做的就是连接string一个object肯定会显示的[object Object]你需要做的是使用逗号,而不是+里面console.log()

替换console.log("error message is "+error.message);console.log("error message is ", error.message);

希望这有帮助。


推荐阅读