The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Report unhandled 500s to Sentry (#27325)
Paul Rastoin6ca2ff6ee286
diff --git a/packages/twenty-server/src/engine/api/graphql/direct-execution/direct-execution.service.ts b/packages/twenty-server/src/engine/api/graphql/direct-execution/direct-execution.service.tsindex ff878bbe3d1..da79d0e6aa4 100644--- a/packages/twenty-server/src/engine/api/graphql/direct-execution/direct-execution.service.ts+++ b/packages/twenty-server/src/engine/api/graphql/direct-execution/direct-execution.service.ts@@ -68,6 +68,7 @@ import { UpdateManyResolverFactory } from 'src/engine/api/graphql/workspace-resoimport { UpdateOneResolverFactory } from 'src/engine/api/graphql/workspace-resolver-builder/factories/update-one-resolver.factory';import { type WorkspaceResolverBuilderFactoryInterface } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolver-builder-factory.interface';import { type WorkspaceSchemaBuilderContext } from 'src/engine/api/graphql/workspace-schema-builder/interfaces/workspace-schema-builder-context.interface';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { getGraphqlOperationMetricKeyFromErrorCode } from 'src/engine/core-modules/graphql/utils/get-graphql-operation-metric-key-from-error-code.util';import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';@@ -77,6 +78,7 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twentimport { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';import { buildObjectIdByNameMaps } from 'src/engine/metadata-modules/flat-object-metadata/utils/build-object-id-by-name-maps.util';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';export type DirectExecutionResult = {data?: Record<string, unknown>;@@ -122,6 +124,7 @@ export class DirectExecutionService {private readonly restoreOneResolverFactory: RestoreOneResolverFactory,private readonly restoreManyResolverFactory: RestoreManyResolverFactory,private readonly mergeManyResolverFactory: MergeManyResolverFactory,+ private readonly exceptionHandlerService: ExceptionHandlerService,) {this.queryCostHistogram = this.metricsService.getMeter()@@ -441,6 +444,10 @@ export class DirectExecutionService {workspaceQueryRunnerGraphqlApiExceptionHandler(error);} catch (graphqlError) {if (graphqlError instanceof GraphQLError) {+ if (shouldCaptureException(graphqlError)) {+ this.exceptionHandlerService.captureExceptions([error]);+ }+const json = graphqlError.toJSON();if (json.extensions?.userFriendlyMessage) {@@ -456,6 +463,10 @@ export class DirectExecutionService {}}+ if (shouldCaptureException(error)) {+ this.exceptionHandlerService.captureExceptions([error]);+ }+return {message: error.message,extensions: { code: 'INTERNAL_SERVER_ERROR' },diff --git a/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.tsindex df66df9f286..753917f0ce3 100644--- a/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts+++ b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts@@ -22,8 +22,14 @@ import { type NextFunction, type Request, type Response } from 'express';import { type GraphQLSchema, graphql } from 'graphql';import supertest from 'supertest';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { UnhandledExceptionFilter } from 'src/filters/unhandled-exception.filter';+const EXCEPTION_HANDLER_SERVICE_PROVIDER = {+ provide: ExceptionHandlerService,+ useValue: { captureExceptions: () => [] },+};+// real Nest + Yoga app so a guard refusal reaches the catch-all filter as in productionexport const runGuardedQuery = async ({guard,@@ -52,7 +58,10 @@ export const runGuardedQuery = async ({}),FeatureModule,],- providers: [{ provide: APP_FILTER, useClass: UnhandledExceptionFilter }],+ providers: [+ { provide: APP_FILTER, useClass: UnhandledExceptionFilter },+ EXCEPTION_HANDLER_SERVICE_PROVIDER,+ ],})class RootModule {}@@ -96,7 +105,10 @@ export const runGuardedRestRequest = async ({@Module({controllers: [TestController],- providers: [{ provide: APP_FILTER, useClass: UnhandledExceptionFilter }],+ providers: [+ { provide: APP_FILTER, useClass: UnhandledExceptionFilter },+ EXCEPTION_HANDLER_SERVICE_PROVIDER,+ ],})class RootModule {}diff --git a/packages/twenty-server/src/filters/__tests__/unhandled-exception.filter.spec.ts b/packages/twenty-server/src/filters/__tests__/unhandled-exception.filter.spec.tsindex 88e64f76e06..4586424071c 100644--- a/packages/twenty-server/src/filters/__tests__/unhandled-exception.filter.spec.ts+++ b/packages/twenty-server/src/filters/__tests__/unhandled-exception.filter.spec.ts@@ -1,8 +1,10 @@// oxlint-disable twenty/graphql-resolvers-should-be-guardedimport {+ type ArgumentsHost,type CanActivate,Injectable,Module,+ NotFoundException,UseGuards,} from '@nestjs/common';import { APP_FILTER } from '@nestjs/core';@@ -20,6 +22,7 @@ import { YogaDriver, type YogaDriverConfig } from '@graphql-yoga/nestjs';import { msg } from '@lingui/core/macro';import { type GraphQLSchema, graphql } from 'graphql';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';import {PermissionsException,@@ -72,7 +75,13 @@ class FeatureModule {}}),FeatureModule,],- providers: [{ provide: APP_FILTER, useClass: UnhandledExceptionFilter }],+ providers: [+ { provide: APP_FILTER, useClass: UnhandledExceptionFilter },+ {+ provide: ExceptionHandlerService,+ useValue: { captureExceptions: jest.fn() },+ },+ ],})class RootModuleWithAppFilter {}@@ -99,7 +108,11 @@ const buildSchema = async (const app = moduleRef.createNestApplication();if (registerFilterAtBootstrap) {- app.useGlobalFilters(new UnhandledExceptionFilter());+ app.useGlobalFilters(+ new UnhandledExceptionFilter({+ captureExceptions: jest.fn(),+ } as unknown as ExceptionHandlerService),+ );}await app.init();@@ -142,3 +155,53 @@ describe('UnhandledExceptionFilter global registration', () => {await app.close();});});++describe('UnhandledExceptionFilter Sentry capture', () => {+ const captureExceptions = jest.fn();++ const filter = new UnhandledExceptionFilter({+ captureExceptions,+ } as unknown as ExceptionHandlerService);++ const buildResponse = () => {+ const response = {+ headersSent: false,+ header: jest.fn(),+ getHeader: jest.fn(),+ status: jest.fn(),+ json: jest.fn(),+ };++ response.status.mockReturnValue(response);++ return response;+ };++ const buildHost = (response: ReturnType<typeof buildResponse>) =>+ ({+ switchToHttp: () => ({ getResponse: () => response }),+ }) as unknown as ArgumentsHost;++ afterEach(() => {+ jest.clearAllMocks();+ });++ it('reports an unexpected error answered with 500', () => {+ const exception = new Error('Unexpected failure');+ const response = buildResponse();++ filter.catch(exception, buildHost(response));++ expect(response.status).toHaveBeenCalledWith(500);+ expect(captureExceptions).toHaveBeenCalledWith([exception]);+ });++ it('does not report a 4xx HttpException', () => {+ const response = buildResponse();++ filter.catch(new NotFoundException(), buildHost(response));++ expect(response.status).toHaveBeenCalledWith(404);+ expect(captureExceptions).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-server/src/filters/unhandled-exception.filter.ts b/packages/twenty-server/src/filters/unhandled-exception.filter.tsindex ae046e7bb51..cc4f47963b8 100644--- a/packages/twenty-server/src/filters/unhandled-exception.filter.ts+++ b/packages/twenty-server/src/filters/unhandled-exception.filter.ts@@ -7,9 +7,16 @@ import {import { type Response } from 'express';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+import { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';+// Exceptions thrown before the CORS middleware (e.g. JSON body parsing) would otherwise lack CORS headers@Catch()export class UnhandledExceptionFilter implements ExceptionFilter {+ constructor(+ private readonly exceptionHandlerService: ExceptionHandlerService,+ ) {}+// oxlint-disable-next-line typescript/no-explicit-anycatch(exception: any, host: ArgumentsHost) {const ctx = host.switchToHttp();@@ -36,6 +43,10 @@ export class UnhandledExceptionFilter implements ExceptionFilter {const status =exception instanceof HttpException ? exception.getStatus() : 500;+ if (shouldCaptureException(exception, status)) {+ this.exceptionHandlerService.captureExceptions([exception]);+ }+response.status(status).json(exception.response ?? exception.message);}}