import {ErrorReporting} from '@google-cloud/error-reporting';
import {Providers, Message, LogLevel, Interceptor} from '@btilford/ts-base-core';
import {ErrorMessage} from '@google-cloud/error-reporting/build/src/classes/error-message';
import {internal} from '@btilford/ts-base-core';
import {logLevelFilter} from '../../../core/src/log';
export function registerErrorReporting(errors?: ErrorReporting): ErrorReporting {
if (!errors) {
errors = new ErrorReporting();
}
return Providers.register(errors, ErrorReporting);
}
export interface ErrorBuilder {
(error: ErrorMessage, context: Message): ErrorMessage;
}
export type StackdriverInterceptorOptions = {
errors?: ErrorReporting;
errorBuilder: ErrorBuilder;
filter: (context: Message) => boolean;
}
export const DefaultStackdriverInterceptorOptions: StackdriverInterceptorOptions = {
errorBuilder: (event: ErrorMessage, context: Message) => {
event.setMessage(context.message);
return event;
},
filter: logLevelFilter(LogLevel.ALERT),
};
export function stackdriverInterceptor(options: StackdriverInterceptorOptions = DefaultStackdriverInterceptorOptions): Interceptor {
const log = internal.logger('StackdriverInterceptor');
return function forwardErrors(context: Message): void {
const errors: ErrorReporting = options.errors || Providers.provide(ErrorReporting);
if (errors) {
if (options.filter(context)) {
const errorEvent = options.errorBuilder(errors.event(), context);
errors.report(errorEvent);
}
}
else {
log.warn('Unable to forward event to Stackdriver! No ErrorReporting provider available!');
}
}
}
|