【问题标题】:Angular error handling using catchError(somefunctionthatreturnsanobservable)使用 catchError(somefunctionthatreturnsanobservable) 的角度错误处理
【发布时间】:2019-04-17 22:56:35
【问题描述】:

通过 Angular 文档处理服务中的 HTTP 错误响应,我遇到了这样的事情:

getContext(){
   return this.http.post(this.testUrl, {})
       .pipe(
           catchError(this.handleError)
       )
}

handleError(error: HttpErrorResponse){
    if(error.error instanceof ErrorEvent){
        console.log('An error occurred:', error.error.message);
    } else {
        console.log(
            `Backend returned code ${error.status}` +
            `body was ${error.error}`
        )
    }
    return throwError('Need to fix!');
}

我想知道为什么 this.handleError 没有传递参数(HTTPErrorResponse)以及它如何在不接收参数的情况下工作?

【问题讨论】:

  • catchError(this.handleError) 等于 herecatchError(error => this.handleError(error))
  • @Kos 啊,我明白了。当只有一个参数传递给只接收一个参数的函数时,是否使用此语法? IE。 catchError(function(error){ this.handleError(error) })
  • 是的!但是有一个重要的区别:当像catchError(this.handleError) 这样调用时,调用上下文将是未定义的。将其阅读为catchError(err => { const fn = this.handleError; return fn(err); })。这里 this 将不再是调用的上下文,上下文将为空。所以你将无法在handleError 方法中引用this
  • @Kos 明白了!谢谢。
  • 关于如何在rxjs中正确抛出我可以推荐两篇文章:medium.com/@alexanderposhtaruk/…blog.angularindepth.com/…

标签: angular rxjs


【解决方案1】:

handleError 方法作为回调传递给catchError

doSomething(callback) {
    // Call the callback with arguments
    callback('Hello world');
}
saySomething(param) {
   console.log(param);
}
doSomething(saySomething);

试着想象catchError 正在为你的handleError 函数做同样的事情。会带参数调用它,你只需指定发生错误时调用什么函数。

祝你好运!

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 2019-06-30
    • 2018-01-29
    • 1970-01-01
    • 2019-10-12
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多