簡體   English   中英

如何使用catch錯誤處理角度錯誤

[英]How to handle the error in angular with catch error

我正在使用angular7。這是我的服務。

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)

在這種情況下請幫助我。

這是一個錯誤,指出您未能在可觀察對象中提供流。

當您不向switchMapcombineLatest或本例中的catchError等操作員提供可觀察的內容時,通常會發生這種情況。

只需添加一個

return of(undefined); 

catchError中解決此問題。

您正在從catchError運算符返回undefined。 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();
        })
    )
}

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM