【问题标题】:Displaying Toaster Errors for Bad Http Requests显示错误 Http 请求的 Toaster 错误
【发布时间】:2019-07-16 17:57:26
【问题描述】:

我试图在 Angular 中捕获我的 Web API 引发的错误,并且我想在某些情况下显示用户友好的错误消息。鉴于下面的响应正文,我将如何访问字符串“必须附加 PE 和所有者签名以获得已提交状态”?

{
  "data": {
    "model.WorkflowStepId": [
      "PE and Owner Signature must be attached for a status of Submitted"
    ]
  },
  "exceptionType": "FieldValidation"
}

这是我目前所拥有的,但我被卡住了,因为我目前只显示字符串“model.WorkflowSetId”。

this.spinner = this.certService.updateCert(this.damId, this.certId, this.model)
      .subscribe(response => {
        ...
      }, 
      (errorRes: HttpErrorResponse) => {
        if (errorRes.error && errorRes.error.exceptionType === 'FieldValidation') {
          const errors = errorRes.error.data;
          for(let error in errors)
            this.notificationService.error(error);
        } else {
          console.log(errorRes);
          this.notificationService.error('An unknown error has occurred. Please try again.');
        }
      });

【问题讨论】:

    标签: json angular typescript error-handling


    【解决方案1】:

    你可以这样做:

    if (errorRes.error && errorRes.error.exceptionType === 'FieldValidation') {
       this.notificationService.error(errorRes.error.data.model.WorkflowStepId[0]);
    }
    

    【讨论】:

      【解决方案2】:

      原来“model.WorkflowStepId”实际上是一个字符串。为了捕获它和其他类型的验证错误,我能够遍历错误请求,构建一个字符串,将相同类型的字段验证错误分组为单个消息,并使用烤面包机将这些消息显示给用户。

      if (errorRes.error && errorRes.error.exceptionType === 'FieldValidation') {
          for (var key in errorRes.error.data) {
              for (var i = 0; i < errorRes.error.data[key].length; i++) {
                  errorStr += (errorRes.error.data[key][i]);
                  errorStr += ". ";
              }    
              this.notificationService.error(errorStr);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-29
        • 1970-01-01
        相关资源
        最近更新 更多