sentry-error-handler-strategy.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { ArgumentsHost, ExecutionContext } from '@nestjs/common';
  2. import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
  3. import { setContext } from '@sentry/node';
  4. import { ErrorHandlerStrategy, I18nError, Injector, Job, LogLevel } from '@vendure/core';
  5. import { SentryService } from './sentry.service';
  6. export class SentryErrorHandlerStrategy implements ErrorHandlerStrategy {
  7. private sentryService: SentryService;
  8. init(injector: Injector) {
  9. this.sentryService = injector.get(SentryService);
  10. }
  11. handleServerError(exception: Error, { host }: { host: ArgumentsHost }) {
  12. // We only care about errors which have at least a Warn log level
  13. const shouldLogError = exception instanceof I18nError ? exception.logLevel <= LogLevel.Warn : true;
  14. if (shouldLogError) {
  15. if (host?.getType<GqlContextType>() === 'graphql') {
  16. const gqlContext = GqlExecutionContext.create(host as ExecutionContext);
  17. const info = gqlContext.getInfo();
  18. setContext('GraphQL Error Context', {
  19. fieldName: info.fieldName,
  20. path: info.path,
  21. });
  22. }
  23. const variables = (exception as any).variables;
  24. if (variables) {
  25. setContext('GraphQL Error Variables', variables);
  26. }
  27. this.sentryService.captureException(exception);
  28. }
  29. }
  30. handleWorkerError(exception: Error, { job }: { job: Job }) {
  31. setContext('Worker Context', {
  32. queueName: job.queueName,
  33. jobId: job.id,
  34. });
  35. this.sentryService.captureException(exception);
  36. }
  37. }