From 58c8bda46526226fca1fc009dcc99dc56eca137b Mon Sep 17 00:00:00 2001 From: Christof Marti Date: Mon, 16 Nov 2026 09:43:23 +0100 Subject: [PATCH] Include the end of the failed command's output in error results The JSON result of up, set-up, build and run-user-commands only had the failed command line as message and a generic description, so the actual error, for example Docker's 'Error response from daemon: ...', was only in the log. The new errorOutput property carries the last lines of the failed command's terminal output or standard error, without terminal control sequences, so callers like the Dev Containers extension can report the cause. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/spec-common/errors.ts | 24 +++++++++ src/spec-node/devContainersSpecCLI.ts | 6 ++- src/test/errors.test.ts | 70 +++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 src/test/errors.test.ts diff --git a/src/spec-common/errors.ts b/src/spec-common/errors.ts index 33ea26eae..0b840ae04 100644 --- a/src/spec-common/errors.ts +++ b/src/spec-common/errors.ts @@ -61,3 +61,27 @@ export class ContainerError extends Error implements ContainerErrorInfo { } } } + +const maxErrorOutputLines = 20; +const maxErrorOutputLength = 2000; + +/** + * Returns the end of the output of the failed command that caused an error, without terminal control sequences. + * That is the combined output for commands run in a terminal and the standard error for other commands. + */ +export function getErrorOutput(err: any): string | undefined { + for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < 10; cause = cause.originalError, depth++) { + const output = typeof cause.cmdOutput === 'string' ? cause.cmdOutput : cause.stderr; + if (output?.length) { + const lines = String(output) + .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '') + .split(/\r?\n/) + // Progress output rewrites the line after a carriage return. + .map(line => line.replace(/\r+$/, '').split('\r').pop()!.trimEnd()) + .filter(line => line.trim()); + const text = lines.slice(-maxErrorOutputLines).join('\n'); + return text.length > maxErrorOutputLength ? text.substring(text.length - maxErrorOutputLength) : text || undefined; + } + } + return undefined; +} diff --git a/src/spec-node/devContainersSpecCLI.ts b/src/spec-node/devContainersSpecCLI.ts index 221f9e3fa..9a1f72886 100644 --- a/src/spec-node/devContainersSpecCLI.ts +++ b/src/spec-node/devContainersSpecCLI.ts @@ -12,7 +12,7 @@ import * as jsonc from 'jsonc-parser'; import { createDockerParams, createLog, launch, ProvisionOptions } from './devContainers'; import { SubstitutedConfig, createContainerProperties, envListToObj, inspectDockerImage, isDockerFileConfig, SubstituteConfig, addSubstitution, findContainerAndIdLabels, getCacheFolder, runAsyncHandler, dockerArgOption } from './utils'; import { URI } from 'vscode-uri'; -import { ContainerError } from '../spec-common/errors'; +import { ContainerError, getErrorOutput } from '../spec-common/errors'; import { Log, LogDimensions, LogLevel, makeLog, mapLogLevel } from '../spec-utils/log'; import { probeRemoteEnv, runLifecycleHooks, runRemoteCommand, UserEnvProbe, setupInContainer } from '../spec-common/injectHeadless'; import { extendImage } from './containerFeatures'; @@ -381,6 +381,7 @@ async function doProvision(options: ProvisionOptions, providedIdLabels: string[] outcome: 'error' as 'error', message: err.message, description: err.description, + errorOutput: getErrorOutput(err), containerId: err.containerId, disallowedFeatureId: err.data.disallowedFeatureId, didStopContainer: err.data.didStopContainer, @@ -561,6 +562,7 @@ async function doSetUp({ outcome: 'error' as 'error', message: err.message, description: err.description, + errorOutput: getErrorOutput(err), dispose, }; } @@ -832,6 +834,7 @@ async function doBuild({ outcome: 'error' as 'error', message: err.message, description: err.description, + errorOutput: getErrorOutput(err), dispose, }; } @@ -1041,6 +1044,7 @@ async function doRunUserCommands({ outcome: 'error' as 'error', message: err.message, description: err.description, + errorOutput: getErrorOutput(err), dispose, }; } diff --git a/src/test/errors.test.ts b/src/test/errors.test.ts new file mode 100644 index 000000000..60130ef1f --- /dev/null +++ b/src/test/errors.test.ts @@ -0,0 +1,70 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import { PassThrough } from 'stream'; +import { ContainerError, getErrorOutput } from '../spec-common/errors'; +import { runCommand, runCommandNoPty } from '../spec-common/commonUtils'; +import { nullLog } from '../spec-utils/log'; + +describe('getErrorOutput', () => { + + function failPty(output: string) { + return runCommand({ + ptyExec: async () => ({ + onData: (cb: (data: string) => void) => { + cb(output); + return { dispose() { } }; + }, + resize() { }, + exit: Promise.resolve({ code: 125, signal: undefined }), + terminate: async () => { }, + }), + cmd: 'docker', + args: ['run', 'image'], + output: nullLog, + print: 'off', + }).then(() => assert.fail('Expected the command to fail.'), err => err); + } + + function fail(stdout: string, stderr: string) { + return runCommandNoPty({ + exec: async () => { + const stdoutStream = new PassThrough(); + const stderrStream = new PassThrough(); + return { + stdin: new PassThrough(), stdout: stdoutStream, stderr: stderrStream, + exit: new Promise(resolve => setImmediate(() => { + stdoutStream.end(stdout); + stderrStream.end(stderr); + resolve({ code: 1, signal: null }); + })), + terminate: async () => { }, + }; + }, + cmd: 'docker', + args: ['compose', 'up'], + output: nullLog, + }).then(() => assert.fail('Expected the command to fail.'), err => err); + } + + it('returns the end of the output of the failed command', async () => { + const lines = Array.from({ length: 18 }, (_, i) => `line ${i}`); + const ptyErr = await failPty(`${lines.join('\r\n')}\r\nPulling 10%\rPulling 100%\r\n\r\n\x1b[31mdocker: Error response from daemon: invalid mount config.\x1b[0m\r\n\x1b]0;title\x07Run 'docker run --help' for more information\r\n`); + const err = await fail('stdout', 'Error response from daemon: Conflict.\n'); + const long = getErrorOutput(await fail('', `${'x'.repeat(3000)}END`)); + assert.deepStrictEqual({ + pty: getErrorOutput(new ContainerError({ description: 'An error occurred setting up the container.', originalError: ptyErr })), + noPty: getErrorOutput(new ContainerError({ description: 'An error occurred starting Docker Compose up.', originalError: err })), + long: long && { length: long.length, end: long.slice(-5) }, + noOutput: getErrorOutput(new ContainerError({ description: 'The expected container does not exist.' })), + }, { + pty: [...lines.slice(1), 'Pulling 100%', 'docker: Error response from daemon: invalid mount config.', `Run 'docker run --help' for more information`].join('\n'), + noPty: 'Error response from daemon: Conflict.', + long: { length: 2000, end: 'xxEND' }, + noOutput: undefined, + }); + }); +});