【问题标题】:Angular custom error handler not getting error type from promiseAngular 自定义错误处理程序没有从 Promise 中获取错误类型
【发布时间】:2019-01-27 19:21:50
【问题描述】:

当我的自定义错误处理程序收到的每个错误从承诺中抛出时,它的类型都会丢失

import { HttpErrorResponse } from "@angular/common/http";
import { ErrorHandler, Injectable, Injector, NgZone } from "@angular/core";
import { MatSnackBar } from "@angular/material";

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

    constructor(private injector: Injector) { }

    handleError(error: any): void {
        if (error instanceof HttpErrorResponse) // this needs to be triggered
            this.injector.get(NgZone).run(() => this.injector.get(MatSnackBar).open(error.message))

        console.error(error)
    }

}

findProject(2) 将抛出 HttpErrorResponse,因为项目 2 不存在。

工作

this.projectService.findProject(2).subscribe()

不工作

await this.projectService.findProject(2).toPromise()

不工作

await this.projectService.findProject(2).toPromise().catch(error => { throw error })

不工作

try {
  await this.projectService.findProject(2).toPromise()
} catch (e) {
  console.log(e instanceof HttpErrorResponse) // true
  throw e
}

ProjectService 是一个大摇大摆的生成类,它返回一个 Observable

编辑: 这是handleError方法中的错误对象:

Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"OK","url":"http://localhost:9090/api/project/2","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:9090/api/project/2: 404 OK","error":{"timestamp":1534921795114,"status":404,"error":"Not Found","exception":"de.dlh.lhind.lhindquiz.controller.ResourceNotFoundException","message":"No message available","path":"/api/project/2"}}
    at resolvePromise (zone.js:814)
    at zone.js:724
    at rejected (main.js:105)
    at ...

似乎 promise 将 HttpErrorResponse 包装在一个常规的 Error 周围,而 error.message 确实是请求的对象

【问题讨论】:

  • 不进入if语句,注销'error',它说的类型是什么?
  • 已添加到问题中
  • 有一个非常相似的问题。在 Promise 流中它不起作用,但可以与订阅流一起使用。

标签: angular error-handling promise rxjs custom-error-handling


【解决方案1】:

我刚刚遇到了同样的问题,偶然发现了你的问题。

如果需要,您可以通过在 ErrorHandler 中解开异常来解决此问题(至少在 Angular 7 中)。

if (error.promise && error.rejection) {
    // Promise rejection wrapped by zone.js
    error = error.rejection;
}

// regular error handling code

注意:我根据这个问题使用console.error("%O", error) 找出了包装错误对象的结构:Chrome: Print exception details to console

【讨论】:

  • 感谢在 Ionic Angular Cordova 应用程序中遇到了同样的问题,特别是在 iOS 应用程序中。这条线解决了这个问题。 unwaited 异步方法抛出的所有错误,Angular 错误处理程序都会捕获它们并将它们作为 Promise 返回。
猜你喜欢
  • 1970-01-01
  • 2019-09-22
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 2018-04-29
  • 2011-06-01
  • 1970-01-01
相关资源
最近更新 更多