我有一个 Angular 5 应用程序,使用使用 raven.js 的 sentry.io 进行错误日志记录。
我让这一切正常工作,但不想在开发中运行时记录错误。如何仅在启用生产模式时启用错误日志记录?
我的 app.module.ts 中有以下内容
import * as Raven from 'raven-js';
Raven
.config('https://xxx@sentry.io/xxx')
.install();
export class RavenErrorHandler implements ErrorHandler {
handleError(err: any): void {
Raven.captureException(err);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为值得分享,因为我有一个类似的问题,我想...
app.error-handler.ts
第一步是实现一个工厂提供程序函数,以根据属性返回SentryErrorHanddlerAngular 默认值并接收所需的依赖项作为参数。ErrorHandlerenvironment.production
import { ErrorHandler } from '@angular/core';
import * as Sentry from '@sentry/browser';
import { environment } from '../environments/environment';
export function errorHandlerFactory(toastService: ToastService) {
if (environment.production) {
return new SentryErrorHandler(toastService);
}
return new ErrorHandler();
}
Run Code Online (Sandbox Code Playgroud)
第二步是实现SentryErrorHandler将依赖项接收到构造函数的类(请注意,我没有在类前面加上 @Injectable 装饰器,因为它将被上面的工厂实例化,而不是由 DI 注入)。
export class SentryErrorHandler implements ErrorHandler {
constructor(public toastService: ToastService) {
Sentry.init({
dsn: 'https://<YOUR-SENTRY-KEY>@sentry.io/<YOUR-PROJECT-ID>',
});
}
handleError(error: any) {
Sentry.captureException(error.originalError || error);
this.toastService.show('An error occurs, please try again later.');
throw error;
}
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts
最后,在AppModule提供ErrorHandler已实现的工厂提供程序errorHandlerFactory并指定它需要通过deps属性的一些注入依赖项,该属性将作为参数传递给工厂提供程序函数
import { ErrorHandler } from '@angular/core';
import { errorHandlerFactory } from './app.error-handler';
@NgModule({
//...
providers: [
{ provide: ErrorHandler, useFactory: errorHandlerFactory, deps: [ToastService] },
],
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
请注意,与此相关的所有内容ToastService仅作为示例来表示您希望访问自定义处理程序的外部依赖项。