diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts index 08ea8122fe..482cb6ee05 100644 --- a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts +++ b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts @@ -1,5 +1,6 @@ import { InjectRepository } from '@nestjs/typeorm'; +import { isDefined } from 'twenty-shared/utils'; import { WorkspaceActivationStatus } from 'twenty-shared/workspace'; import { Repository } from 'typeorm'; @@ -11,6 +12,10 @@ import { Processor } from 'src/engine/core-modules/message-queue/decorators/proc import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants'; import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service'; import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity'; +import { + DataSourceException, + DataSourceExceptionCode, +} from 'src/engine/metadata-modules/data-source/data-source.exception'; import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util'; import { WorkspaceDataSourceService } from 'src/engine/workspace-datasource/workspace-datasource.service'; import { MessageChannelSyncStage } from 'src/modules/messaging/common/standard-objects/message-channel.workspace-entity'; @@ -65,11 +70,35 @@ export class MessagingMessagesImportCronJob { ); } } catch (error) { - this.exceptionHandlerService.captureExceptions([error], { - workspace: { + // We had issues with the workspace schema not being found, due + // to users deleting their workspaces in the middle of the cron job + // We only throw an error when the workspace is found & schema not found + if ( + error.code === '42P01' && + error.message.includes('messageChannel" does not exist') + ) { + const refetchedWorkspace = await this.workspaceRepository.findOneBy({ id: activeWorkspace.id, - }, - }); + }); + + if (isDefined(refetchedWorkspace)) { + this.exceptionHandlerService.captureExceptions([error], { + workspace: { + id: activeWorkspace.id, + }, + }); + throw new DataSourceException( + 'Workspace schema not found while the workspace is still active', + DataSourceExceptionCode.DATA_SOURCE_NOT_FOUND, + ); + } + } else { + this.exceptionHandlerService.captureExceptions([error], { + workspace: { + id: activeWorkspace.id, + }, + }); + } } } }