Angular自定义错误处理程序未从Promise获取错误类型 [英] Angular custom error handler not getting error type from promise
问题描述
我的自定义错误处理程序遇到的每个错误都从承诺中抛出时,它的类型就会丢失
When thrown from a promise every Error my custom error handler is getting does loose its type
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不存在.
findProject(2) will throw a HttpErrorResponse since project 2 does not exist.
工作
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
ProjectService is a swagger generated class which returns an Observable
这是handleError方法中的错误对象:
This is the error object in handleError method:
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确实是请求的对象
It seems like the promise wraps the HttpErrorResponse around a regular Error and error.message is indeed the requested object
推荐答案
我刚刚遇到了同样的问题,偶然发现了您的问题.
I just hit the same issue and stumbled upon your question.
如果需要,您似乎可以通过在ErrorHandler中展开异常来解决此问题(至少在Angular 7中如此).
Seems you can fix this (at least in Angular 7) by unwrapping the exception in your ErrorHandler if needed.
if (error.promise && error.rejection) {
// Promise rejection wrapped by zone.js
error = error.rejection;
}
// regular error handling code
注意:我根据以下问题使用 console.error(%O",error)
找出了包装错误对象的结构:
Note: I figured out the structure of the wrapping Error object using console.error("%O", error)
as per this question: Chrome: Print exception details to console
这篇关于Angular自定义错误处理程序未从Promise获取错误类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!