【问题标题】:Angular gives error when trying to handle errors that come from API callsAngular 在尝试处理来自 API 调用的错误时给出错误
【发布时间】:2022-09-30 11:33:37
【问题描述】:

我正在编写角度服务类来访问 API。当一些内部服务器错误响应时,我想向用户发送错误消息。为获取编写的服务,但给出此错误。

core.js:6014 错误类型错误:您在预期流的位置提供了 \'undefined\'。您可以提供 Observable、Promise、Array 或 Iterable。 在 subscribeTo (subscribeTo.js:40:1)

样本.component.ts

this.sampleService.getCurrentStatus(this.Id, fromDateToRest, 
toDateToRest).subscribe(
  (CurrentStatus: any) => {

    if (CurrentStatus && CurrentStatus.length > 0) {
       //do something
    }

    if (CurrentStatus && CurrentStatus.length == 0) {
      this.errorMessage = \"No data!\"
    }
    else {
      this.errorMessage = \"Vehicle not found!\"
    }
  },
  (error)=>{
    if (error.status == 500) {
      this.errorMessage = \"Internal Server Error!\"
    }
  }
);

示例.service.ts

getCurrentStatus(Id: String, fromDateToRest:String, toDateToRest:String): Observable<any> {

let params;
params = Object.assign( { fromDateToRest, toDateToRest } )

const httpOptions = {
  params
}

return this.restService.get<any>(URL,httpOptions);
}

休息服务

get<T>(url: string, httpOptions?: {}) {
  return this.httpClient.get<T>(url , httpOptions);
}

这是错误日志

回复

控制台日志

我读了同样的问题,但仍然没有得到解决方案。

  • 你也可以粘贴你的restService的代码吗?
  • 该错误表明您没有向可观察对象提供有效的数据流。请提供您的完整代码,而不仅仅是您认为问题所在的几个示例。

标签: angular api error-handling


【解决方案1】:

这是你应该更加关注的您在预期流的位置提供了“未定义”

这正是它所说的。您没有向服务和端点提供任何数据。

您必须检查每个步骤中的数据是否正确传递到另一个步骤,即从组件到服务,从服务到端点。

【讨论】:

  • 数据正确传递。发生内部服务器错误时会出现此错误。我想处理它并向用户提供一些自定义消息
  • 因此,尝试更新您的服务以使用 map(data => { // 转换数据 })、catchError(err => { // 处理错误 }) 来处理响应
【解决方案2】:

当 serve 返回错误响应时,需要在错误回调方法中处理。

this.maintenanceService.getCurrentStatus(this.Id, fromDateToRest, toDateToRest).subscribe(
        (currentStatus) => {
            if (currentStatus && currentStatus.length > 0) {
                //do something
            } else if (currentStatus && currentStatus.length === 0) {
                this.errorMessage = "No data!"
            } else if(currentStatus && currentStatus.status === 500) {
                this.errorMessage = current status.error
            }
        },
        (error) => {
            console.log(error);
            // check error status code, if it is 500, then do some actions like you needed below
            if (error.status === 500) {
                this.errorMessage = "Internal Server Error!"
            }
        }
    );

【讨论】:

  • 我试过了。这对我不起作用。它没有出错部分。不打印日志。
  • 你能记录下响应和错误并附上它的截图吗
  • 添加了响应和控制台日志
  • 由于错误对象是作为响应对象发送的,你可以检查一下 currentStatus 对象的状态属性,如下所示 If(currentStatus.status === 500) { this.errorMessage = current status.error}
  • 试过了。但给出同样的错误。
猜你喜欢
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
相关资源
最近更新 更多