当从承诺中抛出每个错误时,我的自定义错误处理程序都会丢失其类型
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 不存在。
Working
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 是一个 swagger 生成的类,它返回一个 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 确实是请求的对象