我有一个这样定义的全局错误处理程序(清除了简化/专有信息):
export class ErrorsHandler extends CommonBase implements ErrorHandler {
constructor(protected loggingService: LoggingService,
private coreService: CoreService {
super(loggingService);
}
handleError(error: Error) {
if (error && error.stack && (error.stack.indexOf(Constants.PACKAGE_NAME) >= 0)) {
this.logSystemError(error, true);
this.coreService.showSystemError(error, this.owner);
}
else {
// Rethrow all other errors.
throw error;
}
}
并且在我的模块(并且只有我的模块)中,它已这样注册为提供程序:
export function errorHandlerFactory(loggingService: LoggingService, coreService: CoreService) {
return new ErrorsHandler(loggingService, coreService);
}
providers: [
{ provide: ErrorHandler, useFactory: errorHandlerFactory, deps: [LoggingService, CoreService] }
]
我的模块被其他人使用,我们一起组成了一个大型应用程序。
我的问题是,即使我尝试过滤仅与我的模块/程序包相关的那些脚本,也会捕获所有脚本错误,因为过滤是在handleError()
内完成的。即使我重新抛出了与我无关的错误(在上面的else
中),其他模块/程序包的开发人员仍在抱怨我在全球范围内捕获所有内容,并且重新抛出的错误他们已经失去了某些上下文/信息
问题是,是否有可能以某种方式限制我的错误处理程序的范围,以仅捕获和处理源自我的模块/包的脚本错误(而完全忽略应用程序中的所有其他脚本错误)?
经过大量的搜索,我唯一想到的就是将try/catch
放在各处,这是我想尽可能避免的事情。
答案 0 :(得分:3)
您可以尝试创建服务-ErrorService
共享context
,然后throw
共享来自global error handler
的错误。然后,您可以catch
来自必需的Component
的错误。
PFB的步骤:
按如下所示创建错误服务:
@Injectable({
providedIn: 'root'
})
export class ErrorService {
constructor() {}
private error = new BehaviorSubject(new Error());
error_message = this.error.asObservable();
changeMessage(e: Error) {
this.error.next(e);
}
}
throw
来自handleError
中ErrorHandler
方法的错误。 PFB代码段:
handleError(error: Error) {
if (error && error.stack &&(error.stack.indexOf(Constants.PACKAGE_NAME) >= 0))
{
this.logSystemError(error, true);
this.coreService.showSystemError(error, this.owner);
}
else {
//`errorService` is the `instance` for `ErrorService Component`
//imported in the defined `ErrorHandler`
this.errorService.changeMessage(error);
// Rethrow all other errors.
throw error;
}
}
使用try-catch
来捕获Component
中的错误。使用error_message
中的ErrorService
。
答案 1 :(得分:1)
我不知道CommonBase
在做什么,因此我不确定这是否可行,但是您可以做的一件事就是稍微改变一下ErrorsHandler
。如果您更改结构并从核心ErrorHandler
派生,而不是实现其接口,则可能会遇到以下类似情况:
import { Injectable, ErrorHandler } from '@angular/core';
@Injectable()
export class ErrorsHandler extends ErrorHandler {
constructor() {
super();
}
handleError(error: any): void {
if(error && error.stack && error.stack.indexOf("MyModule") >= 0) {
console.log(`Uff, that was close. Got ${error}`);
return;
}
super.handleError(error);
}
}
我认为这可以为您提供更高的可靠性,并且可以正确传播错误。重新抛出该错误以某种方式无法正常工作,但我不确定确切原因是100%。
希望对您有帮助!