如何使用catch错误处理角度错误

时间:2019-02-06 08:47:18

标签: javascript angular typescript rxjs

我正在使用角度7。这是我的服务。

get(){
return this.http.post(this.url).pipe(
catchError(this.handleError)
)
}

这是错误处理程序代码。

handleError(errorResponse: HttpErrorResponse) {
    if (errorResponse.error instanceof ErrorEvent) {
      return throwError(errorResponse.error.message)
    } else {
      switch (errorResponse.status) {
        case 400:
          return throwError(errorResponse.error.message)
        case 401:
          return throwError(errorResponse.error.message)
        case 409:
          return throwError(errorResponse.error.message)
        case 500:
          return throwError(errorResponse.error.message)
      }
    }
  }

这是按下提交按钮时收到的错误。

core.js:15714 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:41)
    at subscribeToResult (subscribeToResult.js:11)
    at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:43)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59)
    at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError (OuterSubscriber.js:13)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error (InnerSubscriber.js:18)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59)

在这种情况下请帮助我。

2 个答案:

答案 0 :(得分:0)

这是一个错误,指出您未能在可观察对象中提供流。

通常在没有为switchMapcombineLatest或在这种情况下为catchError这样的运算符提供可观察值时发生。

只需添加

return of(undefined); 

在您的catchError中解决此问题。

答案 1 :(得分:0)

您从catchError运算符返回未定义。 catchError运算符希望您返回一个可观察值。

get(){
    return this.http.post(this.url).pipe(
        catchError((err) => {
            // handle the error

            // use the empty() factory method to return an observable
            // that emits nothing and completes
            return empty();
        })
    )
}

参考:empty