refactor(core): Switch plain errors in cli to ApplicationError (#7857)

Ensure all errors in `cli` are `ApplicationError` or children of it and
contain no variables in the message, to continue normalizing all the
errors we report to Sentry

Follow-up to: https://github.com/n8n-io/n8n/pull/7839
This commit is contained in:
Iván Ovejero
2023-11-29 12:25:10 +01:00
committed by GitHub
parent 87def60979
commit c08c5cc37b
58 changed files with 277 additions and 195 deletions

View File

@@ -35,6 +35,7 @@ import { InternalHooks } from '@/InternalHooks';
import { TagRepository } from '@db/repositories/tag.repository';
import { Logger } from '@/Logger';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { ApplicationError } from 'n8n-workflow';
@Service()
export class SourceControlService {
@@ -83,7 +84,7 @@ export class SourceControlService {
false,
);
if (!foldersExisted) {
throw new Error();
throw new ApplicationError('No folders exist');
}
if (!this.gitService.git) {
await this.initGitService();
@@ -94,7 +95,7 @@ export class SourceControlService {
branches.current !==
this.sourceControlPreferencesService.sourceControlPreferences.branchName
) {
throw new Error();
throw new ApplicationError('Branch is not set up correctly');
}
} catch (error) {
throw new BadRequestError(
@@ -195,7 +196,7 @@ export class SourceControlService {
await this.gitService.pull();
} catch (error) {
this.logger.error(`Failed to reset workfolder: ${(error as Error).message}`);
throw new Error(
throw new ApplicationError(
'Unable to fetch updates from git - your folder might be out of sync. Try reconnecting from the Source Control settings page.',
);
}

View File

@@ -22,6 +22,7 @@ import { sourceControlFoldersExistCheck } from './sourceControlHelper.ee';
import type { User } from '@db/entities/User';
import { getInstanceOwner } from '../../UserManagement/UserManagementHelper';
import { Logger } from '@/Logger';
import { ApplicationError } from 'n8n-workflow';
@Service()
export class SourceControlGitService {
@@ -43,7 +44,7 @@ export class SourceControlGitService {
});
this.logger.debug(`Git binary found: ${gitResult.toString()}`);
} catch (error) {
throw new Error(`Git binary not found: ${(error as Error).message}`);
throw new ApplicationError('Git binary not found', { cause: error });
}
try {
const sshResult = execSync('ssh -V', {
@@ -51,7 +52,7 @@ export class SourceControlGitService {
});
this.logger.debug(`SSH binary found: ${sshResult.toString()}`);
} catch (error) {
throw new Error(`SSH binary not found: ${(error as Error).message}`);
throw new ApplicationError('SSH binary not found', { cause: error });
}
return true;
}
@@ -114,7 +115,7 @@ export class SourceControlGitService {
private async checkRepositorySetup(): Promise<boolean> {
if (!this.git) {
throw new Error('Git is not initialized (async)');
throw new ApplicationError('Git is not initialized (async)');
}
if (!(await this.git.checkIsRepo())) {
return false;
@@ -129,7 +130,7 @@ export class SourceControlGitService {
private async hasRemote(remote: string): Promise<boolean> {
if (!this.git) {
throw new Error('Git is not initialized (async)');
throw new ApplicationError('Git is not initialized (async)');
}
try {
const remotes = await this.git.getRemotes(true);
@@ -141,7 +142,7 @@ export class SourceControlGitService {
return true;
}
} catch (error) {
throw new Error(`Git is not initialized ${(error as Error).message}`);
throw new ApplicationError('Git is not initialized', { cause: error });
}
this.logger.debug(`Git remote not found: ${remote}`);
return false;
@@ -155,7 +156,7 @@ export class SourceControlGitService {
user: User,
): Promise<void> {
if (!this.git) {
throw new Error('Git is not initialized (Promise)');
throw new ApplicationError('Git is not initialized (Promise)');
}
if (sourceControlPreferences.initRepo) {
try {
@@ -193,7 +194,7 @@ export class SourceControlGitService {
async setGitUserDetails(name: string, email: string): Promise<void> {
if (!this.git) {
throw new Error('Git is not initialized (setGitUserDetails)');
throw new ApplicationError('Git is not initialized (setGitUserDetails)');
}
await this.git.addConfig('user.email', email);
await this.git.addConfig('user.name', name);
@@ -201,7 +202,7 @@ export class SourceControlGitService {
async getBranches(): Promise<{ branches: string[]; currentBranch: string }> {
if (!this.git) {
throw new Error('Git is not initialized (getBranches)');
throw new ApplicationError('Git is not initialized (getBranches)');
}
try {
@@ -218,13 +219,13 @@ export class SourceControlGitService {
currentBranch: current,
};
} catch (error) {
throw new Error(`Could not get remote branches from repository ${(error as Error).message}`);
throw new ApplicationError('Could not get remote branches from repository', { cause: error });
}
}
async setBranch(branch: string): Promise<{ branches: string[]; currentBranch: string }> {
if (!this.git) {
throw new Error('Git is not initialized (setBranch)');
throw new ApplicationError('Git is not initialized (setBranch)');
}
await this.git.checkout(branch);
await this.git.branch([`--set-upstream-to=${SOURCE_CONTROL_ORIGIN}/${branch}`, branch]);
@@ -233,7 +234,7 @@ export class SourceControlGitService {
async getCurrentBranch(): Promise<{ current: string; remote: string }> {
if (!this.git) {
throw new Error('Git is not initialized (getCurrentBranch)');
throw new ApplicationError('Git is not initialized (getCurrentBranch)');
}
const currentBranch = (await this.git.branch()).current;
return {
@@ -244,7 +245,7 @@ export class SourceControlGitService {
async diffRemote(): Promise<DiffResult | undefined> {
if (!this.git) {
throw new Error('Git is not initialized (diffRemote)');
throw new ApplicationError('Git is not initialized (diffRemote)');
}
const currentBranch = await this.getCurrentBranch();
if (currentBranch.remote) {
@@ -256,7 +257,7 @@ export class SourceControlGitService {
async diffLocal(): Promise<DiffResult | undefined> {
if (!this.git) {
throw new Error('Git is not initialized (diffLocal)');
throw new ApplicationError('Git is not initialized (diffLocal)');
}
const currentBranch = await this.getCurrentBranch();
if (currentBranch.remote) {
@@ -268,14 +269,14 @@ export class SourceControlGitService {
async fetch(): Promise<FetchResult> {
if (!this.git) {
throw new Error('Git is not initialized (fetch)');
throw new ApplicationError('Git is not initialized (fetch)');
}
return this.git.fetch();
}
async pull(options: { ffOnly: boolean } = { ffOnly: true }): Promise<PullResult> {
if (!this.git) {
throw new Error('Git is not initialized (pull)');
throw new ApplicationError('Git is not initialized (pull)');
}
const params = {};
if (options.ffOnly) {
@@ -293,7 +294,7 @@ export class SourceControlGitService {
): Promise<PushResult> {
const { force, branch } = options;
if (!this.git) {
throw new Error('Git is not initialized ({)');
throw new ApplicationError('Git is not initialized ({)');
}
if (force) {
return this.git.push(SOURCE_CONTROL_ORIGIN, branch, ['-f']);
@@ -303,7 +304,7 @@ export class SourceControlGitService {
async stage(files: Set<string>, deletedFiles?: Set<string>): Promise<string> {
if (!this.git) {
throw new Error('Git is not initialized (stage)');
throw new ApplicationError('Git is not initialized (stage)');
}
if (deletedFiles?.size) {
try {
@@ -319,7 +320,7 @@ export class SourceControlGitService {
options: { hard: boolean; target: string } = { hard: true, target: 'HEAD' },
): Promise<string> {
if (!this.git) {
throw new Error('Git is not initialized (Promise)');
throw new ApplicationError('Git is not initialized (Promise)');
}
if (options?.hard) {
return this.git.raw(['reset', '--hard', options.target]);
@@ -331,14 +332,14 @@ export class SourceControlGitService {
async commit(message: string): Promise<CommitResult> {
if (!this.git) {
throw new Error('Git is not initialized (commit)');
throw new ApplicationError('Git is not initialized (commit)');
}
return this.git.commit(message);
}
async status(): Promise<StatusResult> {
if (!this.git) {
throw new Error('Git is not initialized (status)');
throw new ApplicationError('Git is not initialized (status)');
}
const statusResult = await this.git.status();
return statusResult;

View File

@@ -8,7 +8,7 @@ import {
SOURCE_CONTROL_WORKFLOW_EXPORT_FOLDER,
} from './constants';
import glob from 'fast-glob';
import { jsonParse } from 'n8n-workflow';
import { ApplicationError, jsonParse } from 'n8n-workflow';
import { readFile as fsReadFile } from 'fs/promises';
import { Credentials, InstanceSettings } from 'n8n-core';
import type { IWorkflowToImport } from '@/Interfaces';
@@ -63,7 +63,7 @@ export class SourceControlImportService {
const globalOwnerRole = await Container.get(RoleService).findGlobalOwnerRole();
if (!globalOwnerRole) {
throw new Error(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
throw new ApplicationError(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
}
return globalOwnerRole;
@@ -73,7 +73,7 @@ export class SourceControlImportService {
const credentialOwnerRole = await Container.get(RoleService).findCredentialOwnerRole();
if (!credentialOwnerRole) {
throw new Error(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
throw new ApplicationError(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
}
return credentialOwnerRole;
@@ -83,7 +83,7 @@ export class SourceControlImportService {
const workflowOwnerRole = await Container.get(RoleService).findWorkflowOwnerRole();
if (!workflowOwnerRole) {
throw new Error(`Failed to find owner workflow role. ${UM_FIX_INSTRUCTION}`);
throw new ApplicationError(`Failed to find owner workflow role. ${UM_FIX_INSTRUCTION}`);
}
return workflowOwnerRole;
@@ -255,7 +255,9 @@ export class SourceControlImportService {
['id'],
);
if (upsertResult?.identifiers?.length !== 1) {
throw new Error(`Failed to upsert workflow ${importedWorkflow.id ?? 'new'}`);
throw new ApplicationError('Failed to upsert workflow', {
extra: { workflowId: importedWorkflow.id ?? 'new' },
});
}
// Update workflow owner to the user who exported the workflow, if that user exists
// in the instance, and the workflow doesn't already have an owner
@@ -435,7 +437,7 @@ export class SourceControlImportService {
select: ['id'],
});
if (findByName && findByName.id !== tag.id) {
throw new Error(
throw new ApplicationError(
`A tag with the name <strong>${tag.name}</strong> already exists locally.<br />Please either rename the local tag, or the remote one with the id <strong>${tag.id}</strong> in the tags.json file.`,
);
}

View File

@@ -10,7 +10,7 @@ import {
sourceControlFoldersExistCheck,
} from './sourceControlHelper.ee';
import { InstanceSettings } from 'n8n-core';
import { jsonParse } from 'n8n-workflow';
import { ApplicationError, jsonParse } from 'n8n-workflow';
import {
SOURCE_CONTROL_SSH_FOLDER,
SOURCE_CONTROL_GIT_FOLDER,
@@ -150,7 +150,9 @@ export class SourceControlPreferencesService {
validationError: { target: false },
});
if (validationResult.length > 0) {
throw new Error(`Invalid source control preferences: ${JSON.stringify(validationResult)}`);
throw new ApplicationError('Invalid source control preferences', {
extra: { preferences: validationResult },
});
}
return validationResult;
}
@@ -177,7 +179,7 @@ export class SourceControlPreferencesService {
loadOnStartup: true,
});
} catch (error) {
throw new Error(`Failed to save source control preferences: ${(error as Error).message}`);
throw new ApplicationError('Failed to save source control preferences', { cause: error });
}
}
return this.sourceControlPreferences;