From 3af8b0a4df6e2b23834fdd10cf89ae13c1f0f434 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Fri, 25 Oct 2024 20:17:24 -0700 Subject: [PATCH] Tighten up `throwToolExit`, explain when to use it. (#157561) Documents when to use `throwToolExit` and how to use it. Replaces every invocation of `throw ToolExit` with `throwToolExit` and makes the former impossible; this is so that every user will at least (hypothetically) have the chance to read the documentation attached to `throwToolExit` (and if we change parameters in the future they will all flow through one place). --- packages/flutter_tools/lib/src/artifacts.dart | 4 +- .../flutter_tools/lib/src/base/common.dart | 45 ++++++++++++++----- .../lib/src/commands/channel.dart | 2 +- .../lib/src/custom_devices/custom_device.dart | 6 +-- .../lib/src/drive/web_driver_service.dart | 8 ++-- .../lib/src/runner/flutter_command.dart | 2 +- .../flutter_tools/lib/src/web/chrome.dart | 2 +- .../flutter_tools/lib/src/web_template.dart | 4 +- 8 files changed, 48 insertions(+), 25 deletions(-) diff --git a/packages/flutter_tools/lib/src/artifacts.dart b/packages/flutter_tools/lib/src/artifacts.dart index 2b1705058e..53906e08be 100644 --- a/packages/flutter_tools/lib/src/artifacts.dart +++ b/packages/flutter_tools/lib/src/artifacts.dart @@ -1295,7 +1295,7 @@ class CachedLocalEngineArtifacts implements Artifacts { return prebuiltPath; } - throw ToolExit('Unable to find a built dart sdk at: "$builtPath" or a prebuilt dart sdk at: "$prebuiltPath"'); + throwToolExit('Unable to find a built dart sdk at: "$builtPath" or a prebuilt dart sdk at: "$prebuiltPath"'); } String _getFlutterPrebuiltsPath() { @@ -1520,7 +1520,7 @@ class CachedLocalWebSdkArtifacts implements Artifacts { return prebuiltPath; } - throw ToolExit('Unable to find a prebuilt dart sdk at: "$prebuiltPath"'); + throwToolExit('Unable to find a prebuilt dart sdk at: "$prebuiltPath"'); } String _getFlutterPrebuiltsPath() { diff --git a/packages/flutter_tools/lib/src/base/common.dart b/packages/flutter_tools/lib/src/base/common.dart index 4ee40046c5..3d18e73902 100644 --- a/packages/flutter_tools/lib/src/base/common.dart +++ b/packages/flutter_tools/lib/src/base/common.dart @@ -2,20 +2,43 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/// Throw a specialized exception for expected situations -/// where the tool should exit with a clear message to the user -/// and no stack trace unless the --verbose option is specified. -/// For example: network errors. +/// Throws a specialized exception to exit with an actionable [message]. +/// +/// A [ToolExit] is interpreted by the `flutter` tool to mean "exit the tool +/// gracefully with a human actionable error [message]", and should be used in +/// scenarios where a human (developer) can make a decision based on the result. +/// +/// For example: +/// +/// - An invalid set of command-line arguments were passed. +/// - The network appears to be unavailable. +/// - The project needs to be modified in some way for a command to succeed. +/// +/// Prefer throwing an error (such as [StateError]) for cases such as: +/// +/// - An internal tool (such as invoking `dart`) returns an unexpected response. +/// - An unrecoverable state is detected deeper in execution. +/// +/// A stack trace is included in the tool output when `--verbose` is specified. +/// +/// While supported, avoid passing `null` for [message]; this is a legacy +/// behavior that is not intended. For example, provide the message directly +/// instead of using a combination of `logger.error` and `throwToolExit`: +/// +/// ```diff +/// - logger.error('Expected --foo to be provided in conjunction with --bar'); +/// - throwToolExit(null); +/// + throwToolExit('Expected --foo to be provided in conjunction with --bar'); +/// ``` Never throwToolExit(String? message, { int? exitCode }) { - throw ToolExit(message, exitCode: exitCode); + throw ToolExit._(message, exitCode: exitCode); } -/// Specialized exception for expected situations -/// where the tool should exit with a clear message to the user -/// and no stack trace unless the --verbose option is specified. -/// For example: network errors. -class ToolExit implements Exception { - ToolExit(this.message, { this.exitCode }); +/// A specialized exception to exit with an actionable [message]. +/// +/// See [throwToolExit]. +final class ToolExit implements Exception { + ToolExit._(this.message, { this.exitCode }); final String? message; final int? exitCode; diff --git a/packages/flutter_tools/lib/src/commands/channel.dart b/packages/flutter_tools/lib/src/commands/channel.dart index 1c54fa1513..667e5a7c3e 100644 --- a/packages/flutter_tools/lib/src/commands/channel.dart +++ b/packages/flutter_tools/lib/src/commands/channel.dart @@ -57,7 +57,7 @@ class ChannelCommand extends FlutterCommand { await _switchChannel(rest[0]); return FlutterCommandResult.success(); default: - throw ToolExit('Too many arguments.\n$usage'); + throwToolExit('Too many arguments.\n$usage'); } } diff --git a/packages/flutter_tools/lib/src/custom_devices/custom_device.dart b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart index 25980ab7d3..6ed6fbdc30 100644 --- a/packages/flutter_tools/lib/src/custom_devices/custom_device.dart +++ b/packages/flutter_tools/lib/src/custom_devices/custom_device.dart @@ -218,7 +218,7 @@ class CustomDevicePortForwarder extends DevicePortForwarder { } } - throw ToolExit('Forwarding port for custom device $_deviceName failed after $tries tries.'); + throwToolExit('Forwarding port for custom device $_deviceName failed after $tries tries.'); } @override @@ -357,7 +357,7 @@ class CustomDeviceAppSession { final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; final String? packageName = _appPackage.name; if (packageName == null) { - throw ToolExit('Could not start app, name for $_appPackage is unknown.'); + throwToolExit('Could not start app, name for $_appPackage is unknown.'); } final List interpolated = interpolateCommand( _device._config.runDebugCommand, @@ -768,7 +768,7 @@ class CustomDevice extends Device { if (_config.postBuildCommand != null) { final String? packageName = package.name; if (packageName == null) { - throw ToolExit('Could not start app, name for $package is unknown.'); + throwToolExit('Could not start app, name for $package is unknown.'); } await _tryPostBuild( appName: packageName, diff --git a/packages/flutter_tools/lib/src/drive/web_driver_service.dart b/packages/flutter_tools/lib/src/drive/web_driver_service.dart index 4a0c591436..8958a4150b 100644 --- a/packages/flutter_tools/lib/src/drive/web_driver_service.dart +++ b/packages/flutter_tools/lib/src/drive/web_driver_service.dart @@ -114,18 +114,18 @@ class WebDriverService extends DriverService { ]); if (_runResult != null) { - throw ToolExit( + throwToolExit( 'Application exited before the test started. Check web driver logs ' 'for possible application-side errors.' ); } if (!isAppStarted) { - throw ToolExit('Failed to start application'); + throwToolExit('Failed to start application'); } if (_residentRunner.uri == null) { - throw ToolExit('Unable to connect to the app. URL not available.'); + throwToolExit('Unable to connect to the app. URL not available.'); } if (debuggingOptions.webLaunchUrl != null) { @@ -209,7 +209,7 @@ class WebDriverService extends DriverService { await _residentRunner.cleanupAtFinish(); if (appDidFinishPrematurely) { - throw ToolExit( + throwToolExit( 'Application exited before the test finished. Check web driver logs ' 'for possible application-side errors.' ); diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 4cebe8e7bc..9bc9dd1c32 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -1896,7 +1896,7 @@ Run 'flutter -h' (or 'flutter -h') for available flutter commands and if (_usesTargetOption) { final String targetPath = targetFile; if (!globals.fs.isFileSync(targetPath)) { - throw ToolExit(globals.userMessages.flutterTargetFileMissing(targetPath)); + throwToolExit(globals.userMessages.flutterTargetFileMissing(targetPath)); } } } diff --git a/packages/flutter_tools/lib/src/web/chrome.dart b/packages/flutter_tools/lib/src/web/chrome.dart index c9a5fdab81..bbfc0ccbbe 100644 --- a/packages/flutter_tools/lib/src/web/chrome.dart +++ b/packages/flutter_tools/lib/src/web/chrome.dart @@ -313,7 +313,7 @@ class ChromiumLauncher { if (retry >= kMaxRetries) { errors.forEach(_logger.printError); _logger.printError('Failed to launch browser after $kMaxRetries tries. Command used to launch it: ${args.join(' ')}'); - throw ToolExit( + throwToolExit( 'Failed to launch browser. Make sure you are using an up-to-date ' 'Chrome or Edge. Otherwise, consider using -d web-server instead ' 'and filing an issue at https://github.com/flutter/flutter/issues.', diff --git a/packages/flutter_tools/lib/src/web_template.dart b/packages/flutter_tools/lib/src/web_template.dart index cfe8aa8087..4221911009 100644 --- a/packages/flutter_tools/lib/src/web_template.dart +++ b/packages/flutter_tools/lib/src/web_template.dart @@ -51,7 +51,7 @@ class WebTemplate { } if (!baseHref.startsWith('/')) { - throw ToolExit( + throwToolExit( 'Error: The base href in "web/index.html" must be absolute (i.e. start ' 'with a "/"), but found: `${baseElement!.outerHtml}`.\n' '$_kBasePathExample', @@ -59,7 +59,7 @@ class WebTemplate { } if (!baseHref.endsWith('/')) { - throw ToolExit( + throwToolExit( 'Error: The base href in "web/index.html" must end with a "/", but found: `${baseElement!.outerHtml}`.\n' '$_kBasePathExample', );