Skip to content

Commit

Permalink
Use an error class instead of string matching
Browse files Browse the repository at this point in the history
  • Loading branch information
rudolf committed Feb 22, 2021
1 parent 61ca6cf commit 60f198f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
21 changes: 18 additions & 3 deletions src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ import {
import { MigrateAndConvertFn } from './document_migrator';
import { SavedObjectsMigrationLogger } from '.';

/**
* Error thrown when saved object migrations encounter a corrupt saved object.
* Corrupt saved objects cannot be serialized because:
* - there's no `[type]` property which contains the type attributes
* - the type or namespace in the _id doesn't match the `type` or `namespace`
* properties
*/
export class CorruptSavedObjectError extends Error {
constructor(public readonly rawId: string) {
super(`Unable to migrate the corrupt saved object document with _id: '${rawId}'.`);

// Set the prototype explicitly, see:
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, CorruptSavedObjectError.prototype);
}
}

/**
* Applies the specified migration function to every saved object document in the list
* of raw docs. Any raw docs that are not valid saved objects will simply be passed through.
Expand Down Expand Up @@ -48,9 +65,7 @@ export async function migrateRawDocs(
)
);
} else {
throw new Error(
`Unable to migrate the corrupt saved object document with _id: '${raw._id}'.`
);
throw new CorruptSavedObjectError(raw._id);
}
}
return processedDocs;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { errors as EsErrors } from '@elastic/elasticsearch';
import * as Option from 'fp-ts/lib/Option';
import { performance } from 'perf_hooks';
import { Logger, LogMeta } from '../../logging';
import { CorruptSavedObjectError } from '../migrations/core/migrate_raw_docs';
import { Model, Next, stateActionMachine } from './state_action_machine';
import { State } from './types';

Expand Down Expand Up @@ -165,7 +166,7 @@ export async function migrationStateActionMachine({
logger.error(e);

dumpExecutionLog(logger, logMessagePrefix, executionLog);
if (e.message.startsWith('Unable to migrate the corrupt saved object document')) {
if (e instanceof CorruptSavedObjectError) {
throw new Error(
`${e.message} To allow migrations to proceed, please delete this document from the [${initialState.indexPrefix}_${initialState.kibanaVersion}_001] index.`
);
Expand Down

0 comments on commit 60f198f

Please sign in to comment.