【发布时间】:2017-10-21 20:11:01
【问题描述】:
我尝试创建一个自定义全局ErrorHandler 并按照详细说明here 进行操作
application-error-handler(只是重要的部分)
@Injectable()
export class ApplicationErrorHandler extends ErrorHandler {
constructor(private injector: Injector) {
super(false);
}
handleError(error: any): void {
if (error instanceof ApplicationError || error.originalError instanceof ApplicationError) {
this.addError(error.originalError);
}
else {
super.handleError(error);
}
}
应用模块
providers: [
{
provide: ErrorHandler,
useClass: ApplicationErrorHandler
}
],
app.component(仅重要部分)
public ngOnInit(): void {
const error = new ApplicationError();
error.message = "fehler";
throw error;
}
应用程序错误
export class ApplicationError implements Error {
name: string;
message: string;
httpStatus?: number = 404;
applicationStatus?: number;
errorMessageTranslationkey: string;
handled: boolean = false;
}
在我的 app.component 中,我抛出了一个 ApplicationError(在 ngOnInit 中),我的 ErrorHandler 被成功调用。
但是我在handleError 中的错误始终是Error 类型,而error.originalError 始终是undefined,无论我是否抛出自定义错误并且if 永远不会解析为true。
我不知道为什么以及如何发生这种情况。
我看到的是错误得到了,所以我假设,因为当我调试时我看到error: Error: [object: Object] at viewWrappedDebugError (vendor.bundle.js)
知道可能导致此问题的原因以及如何解决吗?
编辑
怀疑它与调试模式有关。只要我使用enableProdMode(); 启用 prodmode,它就会按预期工作。
这还没有真正回答我的问题。
如何在 Angular 的调试模式下处理我的自定义错误?
【问题讨论】:
-
你能在你抛出错误的地方添加代码块吗?
throw new ApplicationError()?另请注意,@NgModule()providers属性必须是 this 定义中的数组。 -
我在抛出错误的地方添加了代码。
provider是一个错字。我更新了代码
标签: angular typescript error-handling