Skip to content

Move error handling from Program.cs to BaseCommand SetAction delegate#17310

Open
JamesNK wants to merge 3 commits into
mainfrom
jamesnk/move-error-handling-to-basecommand
Open

Move error handling from Program.cs to BaseCommand SetAction delegate#17310
JamesNK wants to merge 3 commits into
mainfrom
jamesnk/move-error-handling-to-basecommand

Conversation

@JamesNK
Copy link
Copy Markdown
Member

@JamesNK JamesNK commented May 20, 2026

Description

Move the OperationCanceledException and generic Exception catch blocks from Program.Main into the BaseCommand try/catch around ExecuteAsync. This centralizes error handling so all commands benefit from consistent cancellation and unexpected error behavior.

Changes

  • BaseCommand.cs: Added catch blocks for OperationCanceledException (when cancelled or ExtensionOperationCanceledException) and generic Exception to the existing try/catch around ExecuteAsync. Also added CliExitCodes.Cancelled to the exit codes that suppress the "see logs at" message since log files don't contain useful context for user-initiated cancellations.
  • Program.cs: Removed the now-redundant catch blocks from the outer try/catch in Main.

Testing

Ran the full CLI test suite — 3345 passed, 3 failed (all pre-existing unrelated failures in RemoteExecutor tests), 12 skipped.

Move the OperationCanceledException and generic Exception catch blocks
from Program.Main into the BaseCommand try/catch around ExecuteAsync.
This centralizes error handling so all commands benefit from consistent
cancellation and unexpected error behavior.

Also suppress log file path display for cancelled commands by adding
CliExitCodes.Cancelled to the suppression list.
@JamesNK JamesNK requested a review from mitchdenny as a code owner May 20, 2026 11:41
Copilot AI review requested due to automatic review settings May 20, 2026 11:41
@JamesNK JamesNK requested a review from davidfowl as a code owner May 20, 2026 11:41
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 20, 2026

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 17310

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 17310"

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors Aspire CLI error handling by moving cancellation (OperationCanceledException) and unexpected exception handling from Program.Main into the centralized BaseCommand action wrapper around ExecuteAsync, aiming for consistent behavior across commands.

Changes:

  • Centralized handling of cancellation and unexpected exceptions in BaseCommand, producing consistent CommandResult/exit codes.
  • Suppressed the “see logs at …” message for additional exit codes (now including Cancelled).
  • Removed the corresponding catch blocks from Program.Main.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/Aspire.Cli/Commands/BaseCommand.cs Adds centralized cancellation/unexpected-exception handling and expands suppression of the log-path message for certain exit codes.
src/Aspire.Cli/Program.cs Removes OperationCanceledException and generic Exception handling from Main.

Comment thread src/Aspire.Cli/Program.cs
Copy link
Copy Markdown
Member

@IEvangelist IEvangelist left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ PR Testing Complete — Approved

Dogfooded the PR build (13.4.0-pr.17310.gba7be86c, matches head ba7be86c) on Windows. Refactor works as intended and delivers a real user-visible improvement.

Scenarios

# Scenario Result
1 Install + version verification ✅ PASS
2 Regression: aspire --help, aspire new aspire-empty ✅ PASS — exit 0, no See logs at hint
3 MissingRequiredArgument (exit 21) suppresses See logs at ✅ PASS
4 Cancelled (exit 130) suppresses See logs at ⚠️ Code-analysis verified (see note below)
5 Unexpected exception path: error displayed + See logs at shown ✅ PASS — key behavioral improvement
Bonus Normal failure (exit 7, FailedToFindProject) still shows See logs at ✅ PASS

Scenario 5 evidence (the key behavioral change)

aspire init --non-interactive in an empty dir triggered an unhandled exception that escapes ExecuteAsync. Output:

❌ An unexpected error occurred: This prompt requires interactive input but the CLI is running in non-interactive mode. This operation does not yet support non-interactive execution.
📄 See logs at C:\Users\…\.aspire\logs\cli_…log
Exit: 1

Pre-PR this would have been caught only by Program.Main's catch (Exception) and surfaced as a generic log entry with nothing useful on the console. Post-PR, the new generic catch in BaseCommand formats the message via InteractionServiceStrings.UnexpectedErrorOccurred, calls interactionService.DisplayError, records telemetry, returns Failure(InvalidCommand), and the post-execution path shows the See logs at hint. 👍

Scenario 3 evidence (suppression preserved)

❌ A template must be specified when running in non-interactive mode. Use 'aspire new <template>'.
Available values: aspire-starter, aspire-ts-cs-starter, aspire-ts-starter, aspire-py-starter, aspire-ts-empty, aspire-empty
Exit: 21

Exit 21, no See logs at hint — correctly suppressed.

Note on scenario 4 (Ctrl+C)

Empirical SIGINT delivery on Windows from non-interactive PowerShell automation is unreliable: child processes spawned with redirected stdin/out share the parent's console, so AttachConsole+GenerateConsoleCtrlEvent can't reach them. Behavior is symmetric with the verified MissingRequiredArgument suppression (same s_suppressErrorLogsMessageExitCodes array, same check) and the new BaseCommandTests plus this PR's manual testing (3345 tests passed) cover the path.

Conclusion

Small, well-scoped refactor with a real UX improvement. No regressions observed.

@github-actions
Copy link
Copy Markdown
Contributor

CLI E2E Tests unknown — 91 passed, 0 failed, 2 unknown (commit ba7be86)

View all recordings
Status Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View recording
AddPackageWhileAppHostRunningDetached ▶️ View recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View recording
AgentInitCommand_DefaultSelection_InstallsDefaultSkills ▶️ View recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View recording
AllPublishMethodsBuildDockerImages ▶️ View recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View recording
AspireInitSingleFileAppHostRunsViaDotnetRunAppHost ▶️ View recording
AspireInitWithExistingAppHostDirRecreatesMissingNuGetConfigAndPreservesFiles ▶️ View recording
AspireInitWithSolutionFileGeneratesAppHostThatBuildsAgainstChannelHive ▶️ View recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View recording
AspireUpdateRemovesOrphanAppHostPackageVersionWhenSdkAlreadyCurrent ▶️ View recording
Banner_DisplayedOnFirstRun ▶️ View recording
Banner_DisplayedWithExplicitFlag ▶️ View recording
Banner_NotDisplayedWithNoLogoFlag ▶️ View recording
CertificatesClean_RemovesCertificates ▶️ View recording
CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate ▶️ View recording
CertificatesTrust_WithUntrustedCert_TrustsCertificate ▶️ View recording
ConfigSetGet_CreatesNestedJsonFormat ▶️ View recording
CreateAndRunAspireStarterProject ▶️ View recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View recording
CreateAndRunEmptyAppHostProject ▶️ View recording
CreateAndRunJavaEmptyAppHostProject ▶️ View recording
CreateAndRunJsReactProject ▶️ View recording
CreateAndRunPythonReactProject ▶️ View recording
CreateAndRunTypeScriptEmptyAppHostProject ▶️ View recording
CreateAndRunTypeScriptStarterProject ▶️ View recording
CreateJavaAppHostWithViteApp ▶️ View recording
DeployK8sBasicApiService ▶️ View recording
DeployK8sWithExternalHelmChart ▶️ View recording
DeployK8sWithGarnet ▶️ View recording
DeployK8sWithMongoDB ▶️ View recording
DeployK8sWithMySql ▶️ View recording
DeployK8sWithPostgres ▶️ View recording
DeployK8sWithRabbitMQ ▶️ View recording
DeployK8sWithRedis ▶️ View recording
DeployK8sWithSqlServer ▶️ View recording
DeployK8sWithValkey ▶️ View recording
DeployTypeScriptAppToKubernetes ▶️ View recording
DescribeCommandResolvesReplicaNames ▶️ View recording
DescribeCommandShowsRunningResources ▶️ View recording
DetachFormatJsonProducesValidJson ▶️ View recording
DetachFormatJsonProducesValidJsonWhenRestartingExistingInstance ▶️ View recording
DoListStepsShowsPipelineSteps ▶️ View recording
DocsCommand_RendersInteractiveMarkdownFromLocalSource ▶️ View recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View recording
DoctorCommand_TypeScriptAppHostReportsMissingConfiguredToolchain ▶️ View recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View recording
GlobalMigration_HandlesCommentsAndTrailingCommas ▶️ View recording
GlobalMigration_HandlesMalformedLegacyJson ▶️ View recording
GlobalMigration_PreservesAllValueTypes ▶️ View recording
GlobalMigration_SkipsWhenNewConfigExists ▶️ View recording
GlobalSettings_MigratedFromLegacyFormat ▶️ View recording
InteractiveCSharpInitCreatesExpectedFiles ▶️ View recording
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View recording
JavaScriptHostingApisRunFromTypeScriptAppHost ▶️ View recording
LatestCliCanStartStableChannelAppHost ▶️ View recording
LatestCliCanStartStableChannelTypeScriptAppHost ▶️ View recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View recording
LogLevelTrace_ProducesTraceEntriesInCliLogFile ▶️ View recording
LogsCommandShowsResourceLogs ▶️ View recording
OtelLogsReturnsStructuredLogsFromStarterApp ▶️ View recording
OtelLogsReturnsStructuredLogsFromStarterAppIsolated ▶️ View recording
PsCommandListsRunningAppHost ▶️ View recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View recording
PublishWithConfigureEnvFileUpdatesEnvOutput ▶️ View recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View recording
PublishWithoutOutputPathUsesAppHostDirectoryDefault ▶️ View recording
ResourceCommand_FailedExecution_DisplaysAppHostLogPathAndLogContainsEntries ▶️ View recording
ResourceCommand_FailsWhenInteractionServiceIsRequired ▶️ View recording
ResourceCommand_SetAndDeleteParameterUpdatesDescribeOutput ▶️ View recording
RestoreGeneratesSdkFiles ▶️ View recording
RestoreGeneratesSdkFiles_WithConfiguredToolchain ▶️ View recording
RestoreRefreshesGeneratedSdkAfterAddingIntegration ▶️ View recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View recording
RunPublishFailureScenarioAsync ▶️ View recording
RunReportsSyntaxErrorsForDotNetAppHost ▶️ View recording
RunReportsSyntaxErrorsForTypeScriptAppHost ▶️ View recording
SecretCrudOnDotNetAppHost ▶️ View recording
SecretCrudOnTypeScriptAppHost ▶️ View recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View recording
StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets ▶️ View recording
StartReportsSyntaxErrorsForDotNetAppHost ▶️ View recording
StartReportsSyntaxErrorsForTypeScriptAppHost ▶️ View recording
StopAllAppHostsFromAppHostDirectory ▶️ View recording
StopJavaPolyglotAppHostUsingApphostDirectory ▶️ View recording
StopNonInteractiveSingleAppHost ▶️ View recording
StopTypeScriptPolyglotAppHostUsingApphostDirectory ▶️ View recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View recording
UnAwaitedChainsCompileWithAutoResolvePromises ▶️ View recording
UpdateProjectChannelToStable_TypeScript_PicksUpStablePackages ▶️ View recording

📹 Recordings uploaded automatically from CI run #26165336380

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants