Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/Aspire.Cli/Commands/BaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ namespace Aspire.Cli.Commands;

internal abstract class BaseCommand : Command
{
private static readonly int[] s_suppressErrorLogsMessageExitCodes = [CliExitCodes.Cancelled, CliExitCodes.MissingRequiredArgument];

protected virtual bool UpdateNotificationsEnabled { get; } = true;

/// <summary>
Expand Down Expand Up @@ -60,6 +62,16 @@ protected BaseCommand(string name, string description, IFeatures features, ICliU
// Error messages have already been displayed by the interaction service.
result = CommandResult.Failure(CliExitCodes.MissingRequiredArgument);
}
catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested || ex is ExtensionOperationCanceledException)
{
result = CommandResult.Cancelled();
}
catch (Exception ex)
{
var errorMessage = string.Format(CultureInfo.CurrentCulture, InteractionServiceStrings.UnexpectedErrorOccurred, ex.Message);
telemetry.RecordError(errorMessage, ex);
result = CommandResult.Failure(CliExitCodes.InvalidCommand, errorMessage);
}

var isErrorExitCode = result.ExitCode != CliExitCodes.Success;

Expand All @@ -82,7 +94,7 @@ protected BaseCommand(string name, string description, IFeatures features, ICliU
// Display the CLI log file path on non-zero exit codes so the user knows
// where to find diagnostic details. Suppress for user-input errors where
// the log wouldn't contain useful context (e.g., missing required arguments).
if (isErrorExitCode && result.ExitCode != CliExitCodes.MissingRequiredArgument)
if (isErrorExitCode && !s_suppressErrorLogsMessageExitCodes.Contains(result.ExitCode))
{
interactionService.DisplayMessage(
KnownEmojis.PageFacingUp,
Expand Down
5 changes: 1 addition & 4 deletions src/Aspire.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -865,12 +865,9 @@ public static async Task<int> Main(string[] args)
// Log exit code for debugging
logger.LogInformation("Exit code: {ExitCode}", exitCode);
}
Comment thread
JamesNK marked this conversation as resolved.
catch (OperationCanceledException ex) when (cancellationManager.IsCancellationRequested || ex is ExtensionOperationCanceledException)
{
exitCode = CliExitCodes.Cancelled;
}
catch (Exception ex)
{
// Should never get here because RootCommand's handler should catch all exceptions, but log just in case.
exitCode = CliExitCodes.InvalidCommand;

logger.LogError(ex, "An unexpected error occurred.");
Expand Down
35 changes: 35 additions & 0 deletions tests/Aspire.Cli.Tests/Commands/BaseCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -270,4 +270,39 @@ public async Task BaseCommand_OnSuccess_DoesNotDisplayLogFilePath()
Assert.DoesNotContain(testInteractionService.DisplayedMessages,
m => m.ConsoleOverride == ConsoleOutput.Error);
}

[Fact]
public async Task BaseCommand_OnUnexpectedException_ReturnsInvalidCommandExitCode_AndDisplaysError()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var testInteractionService = new TestInteractionService();
var backchannelMonitor = new TestAuxiliaryBackchannelMonitor
{
ScanAsyncCallback = _ => throw new InvalidOperationException("Something went wrong")
};

var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => testInteractionService;
options.AuxiliaryBackchannelMonitorFactory = _ => backchannelMonitor;
});
using var provider = services.BuildServiceProvider();

var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("ps");

var exitCode = await result.InvokeAsync().DefaultTimeout();

Assert.Equal(CliExitCodes.InvalidCommand, exitCode);

// Verify error message was displayed
var expectedErrorMessage = string.Format(CultureInfo.CurrentCulture, InteractionServiceStrings.UnexpectedErrorOccurred, "Something went wrong");
Assert.Contains(expectedErrorMessage, testInteractionService.DisplayedErrors);

// Verify log file path was displayed on stderr
var executionContext = provider.GetRequiredService<CliExecutionContext>();
var expectedLogMessage = string.Format(CultureInfo.CurrentCulture, InteractionServiceStrings.SeeLogsAt, executionContext.LogFilePath);
var logMessage = Assert.Single(testInteractionService.DisplayedMessages, m => m.Message == expectedLogMessage);
Assert.Equal(ConsoleOutput.Error, logMessage.ConsoleOverride);
}
}
Loading