diff --git a/code/lib/telemetry/src/sanitize.test.ts b/code/lib/telemetry/src/sanitize.test.ts index f5b3a742d3e6..a3389c83df79 100644 --- a/code/lib/telemetry/src/sanitize.test.ts +++ b/code/lib/telemetry/src/sanitize.test.ts @@ -1,7 +1,23 @@ +/* eslint-disable local-rules/no-uncategorized-errors */ import { sanitizeError, cleanPaths } from './sanitize'; describe(`Errors Helpers`, () => { describe(`sanitizeError`, () => { + it(`Sanitizes ansi codes in error`, () => { + const errorMessage = `\u001B[4mStorybook\u001B[0m`; + let e: any; + try { + throw new Error(errorMessage); + } catch (error) { + e = error; + } + + const sanitizedError = sanitizeError(e); + + expect(sanitizedError.message).toEqual('Storybook'); + expect(sanitizedError.stack).toContain('Error: Storybook'); + }); + it(`Sanitizes current path from error stacktraces`, () => { const errorMessage = `this is a test`; let e: any; diff --git a/code/lib/telemetry/src/sanitize.ts b/code/lib/telemetry/src/sanitize.ts index 4c68ed50db94..a611dbea1a13 100644 --- a/code/lib/telemetry/src/sanitize.ts +++ b/code/lib/telemetry/src/sanitize.ts @@ -12,6 +12,11 @@ function regexpEscape(str: string): string { return str.replace(/[-[/{}()*+?.\\^$|]/g, `\\$&`); } +export function removeAnsiEscapeCodes(input: string): string { + // eslint-disable-next-line no-control-regex + return input.replace(/\u001B\[[0-9;]*m/g, ''); +} + export function cleanPaths(str: string, separator: string = sep): string { if (!str) return str; @@ -35,7 +40,15 @@ export function cleanPaths(str: string, separator: string = sep): string { export function sanitizeError(error: Error, pathSeparator: string = sep) { try { // Hack because Node - error = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error))); + error = JSON.parse( + JSON.stringify(error, [...Object.getOwnPropertyNames(error), 'message', 'name']) + ); + if (error.message) { + error.message = removeAnsiEscapeCodes(error.message); + } + if (error.stack) { + error.stack = removeAnsiEscapeCodes(error.stack); + } // Removes all user paths const errorString = cleanPaths(JSON.stringify(error), pathSeparator);