【问题标题】:Elementary Angular syntax issue with error handler declaration in a service服务中的错误处理程序声明的基本 Angular 语法问题
【发布时间】:2019-02-07 15:41:35
【问题描述】:

在浏览Angular tutorial 并将其转换为我的目的时,我决定将显示的两种错误处理方法合并为一个,因为我喜欢两者的功能。

这是一站式服务,这是教程中的两种方法:

  private handleError1(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred', error.error.message);
    } else {
      console.error(`Backend error code ${error.status}`, 
        `body: ${error.error}`);
    }
    return throwError('Something bad happened');
  }

这样调用,其中Group 是我来自 REST 服务器的类:

  getGroups(): Observable<Group[]> {
    return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
        tap(_ => this.log(`fetched groups`)),
        catchError(this.handleError1)
      );
  }

然后,还有:

  private handleError2<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(`${operation} failed!`, error);
      return of(result as T);
    }
  }

这样称呼:

  getGroups(): Observable<Group[]> {
    return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
        tap(_ => this.log(`fetched groups`)),
        catchError(this.handleError2<Group[]>('getGroups', []))
      );
  }

所以我天真地把我的组合错误处理程序放在一起:

private handleError<T>(error: HttpErrorResponse, 
                   operation = 'operation', result?: T) {
....

但我遇到了问题,因为我不知道如何在 catchError() 中对其进行参数化。 HttpErrorResponse 当它是唯一的参数时,显然以某种方式隐含了它,但是如何呢?

【问题讨论】:

    标签: angular typescript error-handling rxjs


    【解决方案1】:

    我花了更多的时间。

    首先,我确保我拥有最新版本的 TypeScript。我的项目使用的是 3.1.1。

    这是我的方法:

      getProducts(): Observable<Product[]> {
        return this.http.get<Product[]>(this.productUrl).pipe(
          tap(data => console.log('All: ' + JSON.stringify(data))),
          catchError(error => this.handleError<Product[]>(error, 'get', [] ))
        );
      }
    

    这是我的错误处理程序:

      private handleError<T>(err: HttpErrorResponse, operation = 'operation', result?: T) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = '';
        if (err.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          errorMessage = `An error occurred: ${err.error.message}`;
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return throwError(errorMessage);
      }
    

    这段代码没有出现任何编译错误。

    我什至在我的 tsconfig.json 中打开了严格模式:

    "strict": true,
    

    它仍然编译没有语法错误。

    我在这里建立了一个堆栈闪电战:https://stackblitz.com/edit/angular-simple-retrieve-deborahk

    如果您没有看到相同的结果,请告诉我。

    【讨论】:

    • 我从 IntelliJ 得到一个严重的编译错误,说 Error:(62, 13) TS2345: Argument of type '(error: any) =&gt; (error: any) =&gt; Observable&lt;Group[]&gt;' is not assignable to parameter of type '(err: any, caught: Observable&lt;Group[]&gt;) =&gt; ObservableInput&lt;{}&gt;'. Type '(error: any) =&gt; Observable&lt;Group[]&gt;' is not assignable to type 'ObservableInput&lt;{}&gt;'. Property '[Symbol.iterator]' is missing in type '(error: any) =&gt; Observable&lt;Group[]&gt;' but required in type 'Iterable&lt;{}&gt;'.
    • 嗯。我在发布之前在我的代码中尝试过它并且它有效。你有严格的类型检查吗?或者上面没有显示的其他代码?
    • 这是默认设置。当我运行ng serve --open 时,IntelliJ 内置编译器和外部 node.js
    • 你运行的是什么版本的 TypeScript?你的代码和我的基本一样吗?
    • 3.3.3.我刚刚从 3.2.4 升级它。但是我将问题缩小到我在handleError() 的返回语句中使用的奇怪语法,现在很高兴!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多