【问题标题】:Not receiving error response from API in Angular在 Angular 中未收到来自 API 的错误响应
【发布时间】:2021-08-11 22:58:38
【问题描述】:

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

我试过只做console.log(error)、error.text()、JSON.parse(error._body).errors、error.error、error.message 和error.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) 时:

【问题讨论】:

    标签: angular rest http angular-httpclient


    【解决方案1】:

    这是console.log 中很常见的错误,这里发生的情况是您收到的错误实际上是object,而您对+ 符号所做的操作是将string 与object 连接起来这肯定会显示[object Object],您需要做的是在console.log() 中使用逗号, 而不是+。

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

    希望这会有所帮助。

    【讨论】:

    • 确实有帮助,谢谢!遗憾的是它仍然没有收到响应正文,它只是显示“axis.component.ts:507 错误消息是 [server] 的 Http 失败响应:.409 冲突”。您是否知道如何检索该响应?
    • @anoncomp - 您是否记录了整个 error object 而不仅仅是 error.message?
    • @anoncomp - 请尝试记录整个错误对象并将错误粘贴到此处
    • @anoncomp - 你在service 中使用PUT 请求吗?您能否也分享您的HttpService 代码。
    • 它是一个 POST 请求!当我只记录对象时,我粘贴了错误对象的图像。 httpService中的POST方法是importUML(params) { return this.httpClient.post('http://localhost:8081/bruml/import/' + params, ""); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2018-05-28
    • 2012-01-08
    相关资源
    最近更新 更多