Unverified Commit f1cd47ef authored by Zachary Anderson's avatar Zachary Anderson Committed by GitHub

[flutter_tool] Where possible, catch only subtypes of Exception (#51440)

parent 80619f10
...@@ -7,3 +7,4 @@ linter: ...@@ -7,3 +7,4 @@ linter:
rules: rules:
unawaited_futures: true unawaited_futures: true
curly_braces_in_flow_control_structures: true curly_braces_in_flow_control_structures: true
avoid_catches_without_on_clauses: true
...@@ -62,7 +62,8 @@ Future<int> run( ...@@ -62,7 +62,8 @@ Future<int> run(
try { try {
await runner.run(args); await runner.run(args);
return await _exit(0); return await _exit(0);
} catch (error, stackTrace) { // This catches all exceptions to send to crash logging, etc.
} catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
firstError = error; firstError = error;
firstStackTrace = stackTrace; firstStackTrace = stackTrace;
return await _handleToolError( return await _handleToolError(
...@@ -135,7 +136,8 @@ Future<int> _handleToolError( ...@@ -135,7 +136,8 @@ Future<int> _handleToolError(
await _informUserOfCrash(args, error, stackTrace, errorString); await _informUserOfCrash(args, error, stackTrace, errorString);
return _exit(1); return _exit(1);
} catch (error) { // This catch catches all exceptions to ensure the message below is printed.
} catch (error) { // ignore: avoid_catches_without_on_clauses
globals.stdio.stderrWrite( globals.stdio.stderrWrite(
'Unable to generate crash report due to secondary error: $error\n' 'Unable to generate crash report due to secondary error: $error\n'
'please let us know at https://github.com/flutter/flutter/issues.\n', 'please let us know at https://github.com/flutter/flutter/issues.\n',
...@@ -243,7 +245,7 @@ Future<String> _doctorText() async { ...@@ -243,7 +245,7 @@ Future<String> _doctorText() async {
); );
return logger.statusText; return logger.statusText;
} catch (error, trace) { } on Exception catch (error, trace) {
return 'encountered exception: $error\n\n${trace.toString().trim()}\n'; return 'encountered exception: $error\n\n${trace.toString().trim()}\n';
} }
} }
...@@ -271,7 +273,9 @@ Future<int> _exit(int code) async { ...@@ -271,7 +273,9 @@ Future<int> _exit(int code) async {
globals.printTrace('exiting with code $code'); globals.printTrace('exiting with code $code');
exit(code); exit(code);
completer.complete(); completer.complete();
} catch (error, stackTrace) { // This catches all exceptions becauce the error is propagated on the
// completer.
} catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
completer.completeError(error, stackTrace); completer.completeError(error, stackTrace);
} }
}); });
......
...@@ -177,7 +177,7 @@ class AndroidDevice extends Device { ...@@ -177,7 +177,7 @@ class AndroidDevice extends Device {
} finally { } finally {
console.destroy(); console.destroy();
} }
} catch (e) { } on Exception catch (e) {
globals.printTrace('Failed to fetch avd name for emulator at $host:$port: $e'); globals.printTrace('Failed to fetch avd name for emulator at $host:$port: $e');
// If we fail to connect to the device, we should not fail so just return // If we fail to connect to the device, we should not fail so just return
// an empty name. This data is best-effort. // an empty name. This data is best-effort.
...@@ -299,7 +299,7 @@ class AndroidDevice extends Device { ...@@ -299,7 +299,7 @@ class AndroidDevice extends Device {
return true; return true;
} }
globals.printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.39 or later.'); globals.printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.39 or later.');
} catch (error, trace) { } on Exception catch (error, trace) {
globals.printError('Error running ADB: $error', stackTrace: trace); globals.printError('Error running ADB: $error', stackTrace: trace);
} }
...@@ -335,7 +335,7 @@ class AndroidDevice extends Device { ...@@ -335,7 +335,7 @@ class AndroidDevice extends Device {
} }
return true; return true;
} catch (e, stacktrace) { } on Exception catch (e, stacktrace) {
globals.printError('Unexpected failure from adb: $e'); globals.printError('Unexpected failure from adb: $e');
globals.printError('Stacktrace: $stacktrace'); globals.printError('Stacktrace: $stacktrace');
return false; return false;
...@@ -366,7 +366,7 @@ class AndroidDevice extends Device { ...@@ -366,7 +366,7 @@ class AndroidDevice extends Device {
try { try {
final RunResult listOut = await runAdbCheckedAsync(<String>['shell', 'pm', 'list', 'packages', app.id]); final RunResult listOut = await runAdbCheckedAsync(<String>['shell', 'pm', 'list', 'packages', app.id]);
return LineSplitter.split(listOut.stdout).contains('package:${app.id}'); return LineSplitter.split(listOut.stdout).contains('package:${app.id}');
} catch (error) { } on Exception catch (error) {
globals.printTrace('$error'); globals.printTrace('$error');
return false; return false;
} }
...@@ -432,7 +432,7 @@ class AndroidDevice extends Device { ...@@ -432,7 +432,7 @@ class AndroidDevice extends Device {
throwOnError: true, throwOnError: true,
); );
uninstallOut = uninstallResult.stdout; uninstallOut = uninstallResult.stdout;
} catch (error) { } on Exception catch (error) {
globals.printError('adb uninstall failed: $error'); globals.printError('adb uninstall failed: $error');
return false; return false;
} }
...@@ -631,7 +631,7 @@ class AndroidDevice extends Device { ...@@ -631,7 +631,7 @@ class AndroidDevice extends Device {
} }
return LaunchResult.succeeded(observatoryUri: observatoryUri); return LaunchResult.succeeded(observatoryUri: observatoryUri);
} catch (error) { } on Exception catch (error) {
globals.printError('Error waiting for a debug connection: $error'); globals.printError('Error waiting for a debug connection: $error');
return LaunchResult.failed(); return LaunchResult.failed();
} finally { } finally {
...@@ -696,7 +696,7 @@ class AndroidDevice extends Device { ...@@ -696,7 +696,7 @@ class AndroidDevice extends Device {
output = runAdbCheckedSync(<String>[ output = runAdbCheckedSync(<String>[
'shell', '-x', 'logcat', '-v', 'time', '-t', '1' 'shell', '-x', 'logcat', '-v', 'time', '-t', '1'
]); ]);
} catch (error) { } on Exception catch (error) {
globals.printError('Failed to extract the most recent timestamp from the Android log: $error.'); globals.printError('Failed to extract the most recent timestamp from the Android log: $error.');
return null; return null;
} }
......
...@@ -492,7 +492,7 @@ class AndroidSdk { ...@@ -492,7 +492,7 @@ class AndroidSdk {
.map((FileSystemEntity entity) { .map((FileSystemEntity entity) {
try { try {
return Version.parse(entity.basename); return Version.parse(entity.basename);
} catch (error) { } on Exception {
return null; return null;
} }
}) })
...@@ -518,7 +518,7 @@ class AndroidSdk { ...@@ -518,7 +518,7 @@ class AndroidSdk {
.group(1); .group(1);
platformVersion = int.parse(versionString); platformVersion = int.parse(versionString);
} }
} catch (error) { } on Exception {
return null; return null;
} }
...@@ -583,7 +583,7 @@ class AndroidSdk { ...@@ -583,7 +583,7 @@ class AndroidSdk {
return fileSystem.path.join(javaHome, 'bin', 'java'); return fileSystem.path.join(javaHome, 'bin', 'java');
} }
} }
} catch (_) { /* ignore */ } } on Exception catch (_) { /* ignore */ }
} }
// Fallback to PATH based lookup. // Fallback to PATH based lookup.
......
...@@ -93,7 +93,7 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -93,7 +93,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
installPath = globals.fs installPath = globals.fs
.file(globals.fs.path.join(homeDotDir.path, 'system', '.home')) .file(globals.fs.path.join(homeDotDir.path, 'system', '.home'))
.readAsStringSync(); .readAsStringSync();
} catch (e) { } on Exception {
// ignored, installPath will be null, which is handled below // ignored, installPath will be null, which is handled below
} }
if (installPath != null && globals.fs.isDirectorySync(installPath)) { if (installPath != null && globals.fs.isDirectorySync(installPath)) {
...@@ -200,7 +200,7 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -200,7 +200,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
_checkForStudio(directory.path); _checkForStudio(directory.path);
} }
} }
} catch (e) { } on Exception catch (e) {
globals.printTrace('Exception while looking for Android Studio: $e'); globals.printTrace('Exception while looking for Android Studio: $e');
} }
} }
......
...@@ -122,7 +122,7 @@ class AndroidValidator extends DoctorValidator { ...@@ -122,7 +122,7 @@ class AndroidValidator extends DoctorValidator {
final List<String> versionLines = (result.stderr as String).split('\n'); final List<String> versionLines = (result.stderr as String).split('\n');
javaVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; javaVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
} }
} catch (error) { } on Exception catch (error) {
_logger.printTrace(error.toString()); _logger.printTrace(error.toString());
} }
if (javaVersionText == null || javaVersionText.isEmpty) { if (javaVersionText == null || javaVersionText.isEmpty) {
...@@ -287,7 +287,7 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -287,7 +287,7 @@ class AndroidLicenseValidator extends DoctorValidator {
final List<String> versionLines = (result.stderr as String).split('\n'); final List<String> versionLines = (result.stderr as String).split('\n');
javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
} }
} catch (error) { } on Exception catch (error) {
globals.printTrace(error.toString()); globals.printTrace(error.toString());
} }
if (javaVersion == null) { if (javaVersion == null) {
...@@ -389,7 +389,7 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -389,7 +389,7 @@ class AndroidLicenseValidator extends DoctorValidator {
globals.stdio.addStdoutStream(process.stdout), globals.stdio.addStdoutStream(process.stdout),
globals.stdio.addStderrStream(process.stderr), globals.stdio.addStderrStream(process.stderr),
]); ]);
} catch (err, stack) { } on Exception catch (err, stack) {
globals.printTrace('Echoing stdout or stderr from the license subprocess failed:'); globals.printTrace('Echoing stdout or stderr from the license subprocess failed:');
globals.printTrace('$err\n$stack'); globals.printTrace('$err\n$stack');
} }
......
...@@ -128,7 +128,7 @@ class _ManifestAssetBundle implements AssetBundle { ...@@ -128,7 +128,7 @@ class _ManifestAssetBundle implements AssetBundle {
FlutterManifest flutterManifest; FlutterManifest flutterManifest;
try { try {
flutterManifest = FlutterManifest.createFromPath(manifestPath); flutterManifest = FlutterManifest.createFromPath(manifestPath);
} catch (e) { } on Exception catch (e) {
globals.printStatus('Error detected in pubspec.yaml:', emphasis: true); globals.printStatus('Error detected in pubspec.yaml:', emphasis: true);
globals.printError('$e'); globals.printError('$e');
return 1; return 1;
......
...@@ -112,7 +112,9 @@ Future<T> asyncGuard<T>( ...@@ -112,7 +112,9 @@ Future<T> asyncGuard<T>(
if (!completer.isCompleted) { if (!completer.isCompleted) {
completer.complete(result); completer.complete(result);
} }
} catch (e, s) { // This catches all exceptions so that they can be propagated to the
// caller-supplied error handling or the completer.
} catch (e, s) { // ignore: avoid_catches_without_on_clauses
handleError(e, s); handleError(e, s);
} }
}, onError: (Object e, StackTrace s) { }, onError: (Object e, StackTrace s) {
......
...@@ -66,7 +66,7 @@ class Fingerprinter { ...@@ -66,7 +66,7 @@ class Fingerprinter {
final Fingerprint oldFingerprint = Fingerprint.fromJson(fingerprintFile.readAsStringSync()); final Fingerprint oldFingerprint = Fingerprint.fromJson(fingerprintFile.readAsStringSync());
final Fingerprint newFingerprint = buildFingerprint(); final Fingerprint newFingerprint = buildFingerprint();
return oldFingerprint == newFingerprint; return oldFingerprint == newFingerprint;
} catch (e) { } on Exception catch (e) {
// Log exception and continue, fingerprinting is only a performance improvement. // Log exception and continue, fingerprinting is only a performance improvement.
globals.printTrace('Fingerprint check error: $e'); globals.printTrace('Fingerprint check error: $e');
} }
...@@ -77,7 +77,7 @@ class Fingerprinter { ...@@ -77,7 +77,7 @@ class Fingerprinter {
try { try {
final Fingerprint fingerprint = buildFingerprint(); final Fingerprint fingerprint = buildFingerprint();
globals.fs.file(fingerprintPath).writeAsStringSync(fingerprint.toJson()); globals.fs.file(fingerprintPath).writeAsStringSync(fingerprint.toJson());
} catch (e) { } on Exception catch (e) {
// Log exception and continue, fingerprinting is only a performance improvement. // Log exception and continue, fingerprinting is only a performance improvement.
globals.printTrace('Fingerprint write error: $e'); globals.printTrace('Fingerprint write error: $e');
} }
...@@ -103,7 +103,7 @@ class Fingerprint { ...@@ -103,7 +103,7 @@ class Fingerprint {
final Iterable<File> files = inputPaths.map<File>(globals.fs.file); final Iterable<File> files = inputPaths.map<File>(globals.fs.file);
final Iterable<File> missingInputs = files.where((File file) => !file.existsSync()); final Iterable<File> missingInputs = files.where((File file) => !file.existsSync());
if (missingInputs.isNotEmpty) { if (missingInputs.isNotEmpty) {
throw ArgumentError('Missing input files:\n' + missingInputs.join('\n')); throw Exception('Missing input files:\n' + missingInputs.join('\n'));
} }
_checksums = <String, String>{}; _checksums = <String, String>{};
...@@ -116,14 +116,14 @@ class Fingerprint { ...@@ -116,14 +116,14 @@ class Fingerprint {
/// Creates a Fingerprint from serialized JSON. /// Creates a Fingerprint from serialized JSON.
/// ///
/// Throws [ArgumentError], if there is a version mismatch between the /// Throws [Exception], if there is a version mismatch between the
/// serializing framework and this framework. /// serializing framework and this framework.
Fingerprint.fromJson(String jsonData) { Fingerprint.fromJson(String jsonData) {
final Map<String, dynamic> content = castStringKeyedMap(json.decode(jsonData)); final Map<String, dynamic> content = castStringKeyedMap(json.decode(jsonData));
final String version = content['version'] as String; final String version = content['version'] as String;
if (version != globals.flutterVersion.frameworkRevision) { if (version != globals.flutterVersion.frameworkRevision) {
throw ArgumentError('Incompatible fingerprint version: $version'); throw Exception('Incompatible fingerprint version: $version');
} }
_checksums = castStringKeyedMap(content['files'])?.cast<String,String>() ?? <String, String>{}; _checksums = castStringKeyedMap(content['files'])?.cast<String,String>() ?? <String, String>{};
_properties = castStringKeyedMap(content['properties'])?.cast<String,String>() ?? <String, String>{}; _properties = castStringKeyedMap(content['properties'])?.cast<String,String>() ?? <String, String>{};
...@@ -182,8 +182,11 @@ Set<String> readDepfile(String depfilePath) { ...@@ -182,8 +182,11 @@ Set<String> readDepfile(String depfilePath) {
// outfile1 outfile2 : file1.dart file2.dart file3.dart // outfile1 outfile2 : file1.dart file2.dart file3.dart
final String contents = globals.fs.file(depfilePath).readAsStringSync(); final String contents = globals.fs.file(depfilePath).readAsStringSync();
final String dependencies = contents.split(': ')[1]; final List<String> dependencies = contents.split(': ');
return dependencies if (dependencies.length < 2) {
throw Exception('malformed depfile');
}
return dependencies[1]
.replaceAllMapped(_separatorExpr, (Match match) => '${match.group(1)}\n') .replaceAllMapped(_separatorExpr, (Match match) => '${match.group(1)}\n')
.split('\n') .split('\n')
.map<String>((String path) => path.replaceAllMapped(_escapeExpr, (Match match) => match.group(1)).trim()) .map<String>((String path) => path.replaceAllMapped(_escapeExpr, (Match match) => match.group(1)).trim())
......
...@@ -364,7 +364,8 @@ class WindowsStdoutLogger extends StdoutLogger { ...@@ -364,7 +364,8 @@ class WindowsStdoutLogger extends StdoutLogger {
? message ? message
: message.replaceAll('🔥', '') : message.replaceAll('🔥', '')
.replaceAll('✗', 'X') .replaceAll('✗', 'X')
.replaceAll('✓', '√'); .replaceAll('✓', '√')
.replaceAll('🔨', '');
_stdio.stdoutWrite(windowsMessage); _stdio.stdoutWrite(windowsMessage);
} }
} }
......
...@@ -136,7 +136,7 @@ abstract class OperatingSystemUtils { ...@@ -136,7 +136,7 @@ abstract class OperatingSystemUtils {
return findFreePort(ipv6: true); return findFreePort(ipv6: true);
} }
_logger.printTrace('findFreePort failed: $e'); _logger.printTrace('findFreePort failed: $e');
} catch (e) { } on Exception catch (e) {
// Failures are signaled by a return value of 0 from this function. // Failures are signaled by a return value of 0 from this function.
_logger.printTrace('findFreePort failed: $e'); _logger.printTrace('findFreePort failed: $e');
} finally { } finally {
......
...@@ -367,7 +367,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -367,7 +367,7 @@ class _DefaultProcessUtils implements ProcessUtils {
stdioFuture = stdioFuture.timeout(const Duration(seconds: 1)); stdioFuture = stdioFuture.timeout(const Duration(seconds: 1));
} }
await stdioFuture; await stdioFuture;
} catch (_) { } on Exception catch (_) {
// Ignore errors on the process' stdout and stderr streams. Just capture // Ignore errors on the process' stdout and stderr streams. Just capture
// whatever we got, and use the exit code // whatever we got, and use the exit code
} }
...@@ -539,7 +539,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -539,7 +539,7 @@ class _DefaultProcessUtils implements ProcessUtils {
_traceCommand(cli); _traceCommand(cli);
try { try {
return _processManager.runSync(cli, environment: environment).exitCode == 0; return _processManager.runSync(cli, environment: environment).exitCode == 0;
} catch (error) { } on Exception catch (error) {
_logger.printTrace('$cli failed with $error'); _logger.printTrace('$cli failed with $error');
return false; return false;
} }
...@@ -553,7 +553,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -553,7 +553,7 @@ class _DefaultProcessUtils implements ProcessUtils {
_traceCommand(cli); _traceCommand(cli);
try { try {
return (await _processManager.run(cli, environment: environment)).exitCode == 0; return (await _processManager.run(cli, environment: environment)).exitCode == 0;
} catch (error) { } on Exception catch (error) {
_logger.printTrace('$cli failed with $error'); _logger.printTrace('$cli failed with $error');
return false; return false;
} }
......
...@@ -117,7 +117,7 @@ class _DefaultSignals implements Signals { ...@@ -117,7 +117,7 @@ class _DefaultSignals implements Signals {
for (final SignalHandler handler in _handlersList[s]) { for (final SignalHandler handler in _handlersList[s]) {
try { try {
await asyncGuard<void>(() async => handler(s)); await asyncGuard<void>(() async => handler(s));
} catch (e) { } on Exception catch (e) {
if (_errorStreamController.hasListener) { if (_errorStreamController.hasListener) {
_errorStreamController.add(e); _errorStreamController.add(e);
} }
......
...@@ -395,8 +395,7 @@ DarwinArch getIOSArchForName(String arch) { ...@@ -395,8 +395,7 @@ DarwinArch getIOSArchForName(String arch) {
case 'x86_64': case 'x86_64':
return DarwinArch.x86_64; return DarwinArch.x86_64;
} }
assert(false); throw Exception('Unsupported iOS arch name "$arch"');
return null;
} }
String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch darwinArch}) { String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch darwinArch}) {
...@@ -477,8 +476,7 @@ AndroidArch getAndroidArchForName(String platform) { ...@@ -477,8 +476,7 @@ AndroidArch getAndroidArchForName(String platform) {
case 'android-x86': case 'android-x86':
return AndroidArch.x86; return AndroidArch.x86;
} }
assert(false); throw Exception('Unsupported Android arch name "$platform"');
return null;
} }
String getNameForAndroidArch(AndroidArch arch) { String getNameForAndroidArch(AndroidArch arch) {
......
...@@ -582,7 +582,7 @@ class _BuildInstance { ...@@ -582,7 +582,7 @@ class _BuildInstance {
previousFile.deleteSync(); previousFile.deleteSync();
} }
} }
} catch (exception, stackTrace) { } on Exception catch (exception, stackTrace) {
// TODO(jonahwilliams): throw specific exception for expected errors to mark // TODO(jonahwilliams): throw specific exception for expected errors to mark
// as non-fatal. All others should be fatal. // as non-fatal. All others should be fatal.
node.target.clearStamp(environment); node.target.clearStamp(environment);
......
...@@ -115,8 +115,8 @@ class FileHashStore { ...@@ -115,8 +115,8 @@ class FileHashStore {
FileStorage fileStorage; FileStorage fileStorage;
try { try {
fileStorage = FileStorage.fromBuffer(data); fileStorage = FileStorage.fromBuffer(data);
} catch (err) { } on Exception catch (err) {
_logger.printTrace('Filestorage format changed'); _logger.printTrace('Filestorage format changed: $err');
cacheFile.deleteSync(); cacheFile.deleteSync();
return; return;
} }
......
...@@ -374,8 +374,8 @@ class ReleaseIosApplicationBundle extends IosAssetBundle { ...@@ -374,8 +374,8 @@ class ReleaseIosApplicationBundle extends IosAssetBundle {
Future<RunResult> createStubAppFramework(File outputFile, SdkType sdk, { bool include32Bit = true }) async { Future<RunResult> createStubAppFramework(File outputFile, SdkType sdk, { bool include32Bit = true }) async {
try { try {
outputFile.createSync(recursive: true); outputFile.createSync(recursive: true);
} catch (e) { } on Exception catch (e) {
throwToolExit('Failed to create App.framework stub at ${outputFile.path}'); throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
} }
final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_stub_source.'); final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_stub_source.');
...@@ -418,8 +418,8 @@ Future<RunResult> createStubAppFramework(File outputFile, SdkType sdk, { bool in ...@@ -418,8 +418,8 @@ Future<RunResult> createStubAppFramework(File outputFile, SdkType sdk, { bool in
tempDir.deleteSync(recursive: true); tempDir.deleteSync(recursive: true);
} on FileSystemException catch (_) { } on FileSystemException catch (_) {
// Best effort. Sometimes we can't delete things from system temp. // Best effort. Sometimes we can't delete things from system temp.
} catch (e) { } on Exception catch (e) {
throwToolExit('Failed to create App.framework stub at ${outputFile.path}'); throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
} }
} }
} }
...@@ -329,7 +329,7 @@ abstract class MacOSBundleFlutterAssets extends Target { ...@@ -329,7 +329,7 @@ abstract class MacOSBundleFlutterAssets extends Target {
try { try {
final File sourceFile = environment.buildDir.childFile('app.dill'); final File sourceFile = environment.buildDir.childFile('app.dill');
sourceFile.copySync(assetDirectory.childFile('kernel_blob.bin').path); sourceFile.copySync(assetDirectory.childFile('kernel_blob.bin').path);
} catch (err) { } on Exception catch (err) {
throw Exception('Failed to copy app.dill: $err'); throw Exception('Failed to copy app.dill: $err');
} }
// Copy precompiled runtimes. // Copy precompiled runtimes.
...@@ -342,7 +342,7 @@ abstract class MacOSBundleFlutterAssets extends Target { ...@@ -342,7 +342,7 @@ abstract class MacOSBundleFlutterAssets extends Target {
assetDirectory.childFile('vm_snapshot_data').path); assetDirectory.childFile('vm_snapshot_data').path);
globals.fs.file(isolateSnapshotData).copySync( globals.fs.file(isolateSnapshotData).copySync(
assetDirectory.childFile('isolate_snapshot_data').path); assetDirectory.childFile('isolate_snapshot_data').path);
} catch (err) { } on Exception catch (err) {
throw Exception('Failed to copy precompiled runtimes: $err'); throw Exception('Failed to copy precompiled runtimes: $err');
} }
} }
......
...@@ -403,7 +403,7 @@ class Cache { ...@@ -403,7 +403,7 @@ class Cache {
if (!cachedFile.existsSync()) { if (!cachedFile.existsSync()) {
try { try {
await downloadFile(url, cachedFile); await downloadFile(url, cachedFile);
} catch (e) { } on Exception catch (e) {
throwToolExit('Failed to fetch third-party artifact $url: $e'); throwToolExit('Failed to fetch third-party artifact $url: $e');
} }
} }
...@@ -597,7 +597,8 @@ abstract class CachedArtifact extends ArtifactSet { ...@@ -597,7 +597,8 @@ abstract class CachedArtifact extends ArtifactSet {
try { try {
await cache.downloadFile(url, tempFile); await cache.downloadFile(url, tempFile);
status.stop(); status.stop();
} catch (exception) { // The exception is rethrown, so don't catch only Exceptions.
} catch (exception) { // ignore: avoid_catches_without_on_clauses
status.cancel(); status.cancel();
rethrow; rethrow;
} }
......
...@@ -33,7 +33,7 @@ abstract class AnalyzeBase { ...@@ -33,7 +33,7 @@ abstract class AnalyzeBase {
} finally { } finally {
resultsFile.close(); resultsFile.close();
} }
} catch (e) { } on Exception catch (e) {
globals.printError('Failed to save output to "${argResults['write']}": $e'); globals.printError('Failed to save output to "${argResults['write']}": $e');
} }
} }
......
...@@ -104,7 +104,7 @@ class AssembleCommand extends FlutterCommand { ...@@ -104,7 +104,7 @@ class AssembleCommand extends FlutterCommand {
CustomDimensions.commandBuildBundleTargetPlatform: localEnvironment.defines['TargetPlatform'], CustomDimensions.commandBuildBundleTargetPlatform: localEnvironment.defines['TargetPlatform'],
CustomDimensions.commandBuildBundleIsModule: '${futterProject.isModule}', CustomDimensions.commandBuildBundleIsModule: '${futterProject.isModule}',
}; };
} catch (err) { } on Exception {
// We've failed to send usage. // We've failed to send usage.
} }
return const <CustomDimensions, String>{}; return const <CustomDimensions, String>{};
......
...@@ -114,7 +114,7 @@ class AttachCommand extends FlutterCommand { ...@@ -114,7 +114,7 @@ class AttachCommand extends FlutterCommand {
} }
try { try {
return int.parse(stringArg('debug-port')); return int.parse(stringArg('debug-port'));
} catch (error) { } on Exception catch (error) {
throwToolExit('Invalid port for `--debug-port`: $error'); throwToolExit('Invalid port for `--debug-port`: $error');
} }
return null; return null;
...@@ -222,7 +222,7 @@ class AttachCommand extends FlutterCommand { ...@@ -222,7 +222,7 @@ class AttachCommand extends FlutterCommand {
try { try {
isolateDiscoveryProtocol = device.getIsolateDiscoveryProtocol(module); isolateDiscoveryProtocol = device.getIsolateDiscoveryProtocol(module);
observatoryUri = Stream<Uri>.value(await isolateDiscoveryProtocol.uri).asBroadcastStream(); observatoryUri = Stream<Uri>.value(await isolateDiscoveryProtocol.uri).asBroadcastStream();
} catch (_) { } on Exception {
isolateDiscoveryProtocol?.dispose(); isolateDiscoveryProtocol?.dispose();
final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList(); final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList();
for (final ForwardedPort port in ports) { for (final ForwardedPort port in ports) {
...@@ -292,7 +292,7 @@ class AttachCommand extends FlutterCommand { ...@@ -292,7 +292,7 @@ class AttachCommand extends FlutterCommand {
globals.fs.currentDirectory, globals.fs.currentDirectory,
LaunchMode.attach, LaunchMode.attach,
); );
} catch (error) { } on Exception catch (error) {
throwToolExit(error.toString()); throwToolExit(error.toString());
} }
result = await app.runner.waitForAppToFinish(); result = await app.runner.waitForAppToFinish();
......
...@@ -75,7 +75,7 @@ class CleanCommand extends FlutterCommand { ...@@ -75,7 +75,7 @@ class CleanCommand extends FlutterCommand {
for (final String scheme in projectInfo.schemes) { for (final String scheme in projectInfo.schemes) {
xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme); xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme);
} }
} catch (error) { } on Exception catch (error) {
globals.printTrace('Could not clean Xcode workspace: $error'); globals.printTrace('Could not clean Xcode workspace: $error');
} finally { } finally {
xcodeStatus?.stop(); xcodeStatus?.stop();
......
...@@ -264,7 +264,7 @@ class CreateCommand extends FlutterCommand { ...@@ -264,7 +264,7 @@ class CreateCommand extends FlutterCommand {
outputFile.writeAsStringSync(samplesJson); outputFile.writeAsStringSync(samplesJson);
globals.printStatus('Wrote samples JSON to "$outputFilePath"'); globals.printStatus('Wrote samples JSON to "$outputFilePath"');
} }
} catch (e) { } on Exception catch (e) {
throwToolExit('Failed to write samples JSON to "$outputFilePath": $e', exitCode: 2); throwToolExit('Failed to write samples JSON to "$outputFilePath": $e', exitCode: 2);
} }
} }
......
...@@ -175,7 +175,7 @@ class Daemon { ...@@ -175,7 +175,7 @@ class Daemon {
completer.complete(request['result']); completer.complete(request['result']);
} }
} }
} catch (error, trace) { } on Exception catch (error, trace) {
_send(<String, dynamic>{ _send(<String, dynamic>{
'id': id, 'id': id,
'error': _toJsonable(error), 'error': _toJsonable(error),
...@@ -414,7 +414,7 @@ class DaemonDomain extends Domain { ...@@ -414,7 +414,7 @@ class DaemonDomain extends Domain {
return <String, Object>{ return <String, Object>{
'platforms': result, 'platforms': result,
}; };
} catch (err, stackTrace) { } on Exception catch (err, stackTrace) {
sendEvent('log', <String, dynamic>{ sendEvent('log', <String, dynamic>{
'log': 'Failed to parse project metadata', 'log': 'Failed to parse project metadata',
'stackTrace': stackTrace.toString(), 'stackTrace': stackTrace.toString(),
...@@ -596,7 +596,7 @@ class AppDomain extends Domain { ...@@ -596,7 +596,7 @@ class AppDomain extends Domain {
appStartedCompleter: appStartedCompleter, appStartedCompleter: appStartedCompleter,
); );
_sendAppEvent(app, 'stop'); _sendAppEvent(app, 'stop');
} catch (error, trace) { } on Exception catch (error, trace) {
_sendAppEvent(app, 'stop', <String, dynamic>{ _sendAppEvent(app, 'stop', <String, dynamic>{
'error': _toJsonable(error), 'error': _toJsonable(error),
'trace': '$trace', 'trace': '$trace',
...@@ -780,7 +780,7 @@ class DeviceDomain extends Domain { ...@@ -780,7 +780,7 @@ class DeviceDomain extends Domain {
try { try {
final Map<String, Object> response = await _deviceToMap(device); final Map<String, Object> response = await _deviceToMap(device);
sendEvent(eventName, response); sendEvent(eventName, response);
} catch (err) { } on Exception catch (err) {
globals.printError('$err'); globals.printError('$err');
} }
}); });
......
...@@ -261,7 +261,7 @@ $ex ...@@ -261,7 +261,7 @@ $ex
try { try {
await window.setLocation(const math.Point<int>(0, 0)); await window.setLocation(const math.Point<int>(0, 0));
await window.setSize(math.Rectangle<int>(0, 0, x, y)); await window.setSize(math.Rectangle<int>(0, 0, x, y));
} catch (_) { } on Exception {
// Error might be thrown in some browsers. // Error might be thrown in some browsers.
} }
...@@ -278,7 +278,7 @@ $ex ...@@ -278,7 +278,7 @@ $ex
try { try {
await testRunner(<String>[testFile], environment); await testRunner(<String>[testFile], environment);
} catch (error, stackTrace) { } on Exception catch (error, stackTrace) {
if (error is ToolExit) { if (error is ToolExit) {
rethrow; rethrow;
} }
......
...@@ -52,8 +52,8 @@ class GenerateCommand extends FlutterCommand { ...@@ -52,8 +52,8 @@ class GenerateCommand extends FlutterCommand {
globals.printError(stackData[0] as String); globals.printError(stackData[0] as String);
globals.printError(stackData[1] as String); globals.printError(stackData[1] as String);
globals.printError(StackTrace.fromString(stackData[2] as String).toString()); globals.printError(StackTrace.fromString(stackData[2] as String).toString());
} catch (err) { } on Exception catch (err) {
globals.printError('Error reading error in ${errorFile.path}'); globals.printError('Error reading error in ${errorFile.path}: $err');
} }
} }
return FlutterCommandResult.fail(); return FlutterCommandResult.fail();
......
...@@ -98,7 +98,8 @@ class PackagesGetCommand extends FlutterCommand { ...@@ -98,7 +98,8 @@ class PackagesGetCommand extends FlutterCommand {
); );
pubGetTimer.stop(); pubGetTimer.stop();
flutterUsage.sendTiming('pub', 'get', pubGetTimer.elapsed, label: 'success'); flutterUsage.sendTiming('pub', 'get', pubGetTimer.elapsed, label: 'success');
} catch (_) { // Not limiting to catching Exception because the exception is rethrown.
} catch (_) { // ignore: avoid_catches_without_on_clauses
pubGetTimer.stop(); pubGetTimer.stop();
flutterUsage.sendTiming('pub', 'get', pubGetTimer.elapsed, label: 'failure'); flutterUsage.sendTiming('pub', 'get', pubGetTimer.elapsed, label: 'failure');
rethrow; rethrow;
......
...@@ -420,7 +420,7 @@ class RunCommand extends RunCommandBase { ...@@ -420,7 +420,7 @@ class RunCommand extends RunCommandBase {
dillOutputPath: stringArg('output-dill'), dillOutputPath: stringArg('output-dill'),
ipv6: ipv6, ipv6: ipv6,
); );
} catch (error) { } on Exception catch (error) {
throwToolExit(error.toString()); throwToolExit(error.toString());
} }
final DateTime appStartedTime = systemClock.now(); final DateTime appStartedTime = systemClock.now();
......
...@@ -116,7 +116,7 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -116,7 +116,7 @@ class ScreenshotCommand extends FlutterCommand {
); );
try { try {
await device.takeScreenshot(outputFile); await device.takeScreenshot(outputFile);
} catch (error) { } on Exception catch (error) {
throwToolExit('Error taking screenshot: $error'); throwToolExit('Error taking screenshot: $error');
} }
_showOutputFileInfo(outputFile); _showOutputFileInfo(outputFile);
......
...@@ -150,7 +150,7 @@ class ArtifactUnpacker { ...@@ -150,7 +150,7 @@ class ArtifactUnpacker {
} else { } else {
globals.printTrace('Artifacts for version $targetHash already present.'); globals.printTrace('Artifacts for version $targetHash already present.');
} }
} catch (error, stackTrace) { } on Exception catch (error, stackTrace) {
globals.printError(stackTrace.toString()); globals.printError(stackTrace.toString());
globals.printError(error.toString()); globals.printError(error.toString());
return false; return false;
...@@ -200,8 +200,8 @@ class ArtifactUnpacker { ...@@ -200,8 +200,8 @@ class ArtifactUnpacker {
} }
globals.printTrace('Copied artifacts from $sourceDirectory.'); globals.printTrace('Copied artifacts from $sourceDirectory.');
} catch (e, stackTrace) { } on Exception catch (e, stackTrace) {
globals.printError(e.message as String); globals.printError(e.toString());
globals.printError(stackTrace.toString()); globals.printError(stackTrace.toString());
return false; return false;
} }
......
...@@ -210,7 +210,7 @@ class UpgradeCommandRunner { ...@@ -210,7 +210,7 @@ class UpgradeCommandRunner {
throwOnError: true, throwOnError: true,
workingDirectory: workingDirectory, workingDirectory: workingDirectory,
); );
} catch (e) { } on Exception {
throwToolExit( throwToolExit(
'Unable to upgrade Flutter: no origin repository configured. ' 'Unable to upgrade Flutter: no origin repository configured. '
"Run 'git remote add origin " "Run 'git remote add origin "
...@@ -279,7 +279,7 @@ class UpgradeCommandRunner { ...@@ -279,7 +279,7 @@ class UpgradeCommandRunner {
final FlutterVersion newFlutterVersion = FlutterVersion(const SystemClock(), workingDirectory); final FlutterVersion newFlutterVersion = FlutterVersion(const SystemClock(), workingDirectory);
alreadyUpToDate = newFlutterVersion.channel == oldFlutterVersion.channel && alreadyUpToDate = newFlutterVersion.channel == oldFlutterVersion.channel &&
newFlutterVersion.frameworkRevision == oldFlutterVersion.frameworkRevision; newFlutterVersion.frameworkRevision == oldFlutterVersion.frameworkRevision;
} catch (e) { } on Exception catch (e) {
globals.printTrace('Failed to determine FlutterVersion after upgrade fast-forward: $e'); globals.printTrace('Failed to determine FlutterVersion after upgrade fast-forward: $e');
} }
return alreadyUpToDate; return alreadyUpToDate;
......
...@@ -116,8 +116,8 @@ class VersionCommand extends FlutterCommand { ...@@ -116,8 +116,8 @@ class VersionCommand extends FlutterCommand {
throwOnError: true, throwOnError: true,
workingDirectory: Cache.flutterRoot, workingDirectory: Cache.flutterRoot,
); );
} catch (e) { } on Exception catch (e) {
throwToolExit('Unable to checkout version branch for version $version.'); throwToolExit('Unable to checkout version branch for version $version: $e');
} }
final FlutterVersion flutterVersion = FlutterVersion(); final FlutterVersion flutterVersion = FlutterVersion();
......
...@@ -180,7 +180,8 @@ class _DefaultPub implements Pub { ...@@ -180,7 +180,8 @@ class _DefaultPub implements Pub {
retry: true, retry: true,
); );
status.stop(); status.stop();
} catch (exception) { // The exception is rethrown, so don't catch only Exceptions.
} catch (exception) { // ignore: avoid_catches_without_on_clauses
status.cancel(); status.cancel();
rethrow; rethrow;
} }
...@@ -322,7 +323,7 @@ class _DefaultPub implements Pub { ...@@ -322,7 +323,7 @@ class _DefaultPub implements Pub {
globals.stdio.addStdoutStream(process.stdout), globals.stdio.addStdoutStream(process.stdout),
globals.stdio.addStderrStream(process.stderr), globals.stdio.addStderrStream(process.stderr),
]); ]);
} catch (err, stack) { } on Exception catch (err, stack) {
globals.printTrace('Echoing stdout or stderr from the pub subprocess failed:'); globals.printTrace('Echoing stdout or stderr from the pub subprocess failed:');
globals.printTrace('$err\n$stack'); globals.printTrace('$err\n$stack');
} }
......
...@@ -116,7 +116,7 @@ abstract class DesktopDevice extends Device { ...@@ -116,7 +116,7 @@ abstract class DesktopDevice extends Device {
final Uri observatoryUri = await observatoryDiscovery.uri; final Uri observatoryUri = await observatoryDiscovery.uri;
onAttached(package, buildMode, process); onAttached(package, buildMode, process);
return LaunchResult.succeeded(observatoryUri: observatoryUri); return LaunchResult.succeeded(observatoryUri: observatoryUri);
} catch (error) { } on Exception catch (error) {
globals.printError('Error waiting for a debug connection: $error'); globals.printError('Error waiting for a debug connection: $error');
return LaunchResult.failed(); return LaunchResult.failed();
} finally { } finally {
......
...@@ -238,7 +238,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations { ...@@ -238,7 +238,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations {
List<int> bytes; List<int> bytes;
try { try {
bytes = await content.contentsAsBytes(); bytes = await content.contentsAsBytes();
} catch (e) { } on Exception catch (e) {
return e; return e;
} }
final String fileContents = base64.encode(bytes); final String fileContents = base64.encode(bytes);
...@@ -251,7 +251,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations { ...@@ -251,7 +251,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations {
'fileContents': fileContents, 'fileContents': fileContents,
}, },
); );
} catch (error) { } on Exception catch (error) {
globals.printTrace('DevFS: Failed to write $deviceUri: $error'); globals.printTrace('DevFS: Failed to write $deviceUri: $error');
} }
} }
...@@ -319,7 +319,7 @@ class _DevFSHttpWriter { ...@@ -319,7 +319,7 @@ class _DevFSHttpWriter {
onError: (dynamic error) { globals.printTrace('error: $error'); }, onError: (dynamic error) { globals.printTrace('error: $error'); },
cancelOnError: true); cancelOnError: true);
break; break;
} catch (error, trace) { } on Exception catch (error, trace) {
if (!_completer.isCompleted) { if (!_completer.isCompleted) {
globals.printTrace('Error writing "$deviceUri" to DevFS: $error'); globals.printTrace('Error writing "$deviceUri" to DevFS: $error');
if (retry > 0) { if (retry > 0) {
...@@ -527,7 +527,7 @@ class DevFS { ...@@ -527,7 +527,7 @@ class DevFS {
} on SocketException catch (socketException, stackTrace) { } on SocketException catch (socketException, stackTrace) {
globals.printTrace('DevFS sync failed. Lost connection to device: $socketException'); globals.printTrace('DevFS sync failed. Lost connection to device: $socketException');
throw DevFSException('Lost connection to device.', socketException, stackTrace); throw DevFSException('Lost connection to device.', socketException, stackTrace);
} catch (exception, stackTrace) { } on Exception catch (exception, stackTrace) {
globals.printError('Could not update files on device: $exception'); globals.printError('Could not update files on device: $exception');
throw DevFSException('Sync failed', exception, stackTrace); throw DevFSException('Sync failed', exception, stackTrace);
} }
......
...@@ -187,7 +187,7 @@ class Doctor { ...@@ -187,7 +187,7 @@ class Doctor {
ValidationResult result; ValidationResult result;
try { try {
result = await asyncGuard<ValidationResult>(() => validator.validate()); result = await asyncGuard<ValidationResult>(() => validator.validate());
} catch (exception) { } on Exception catch (exception) {
// We're generating a summary, so drop the stack trace. // We're generating a summary, so drop the stack trace.
result = ValidationResult.crash(exception); result = ValidationResult.crash(exception);
} }
...@@ -269,10 +269,10 @@ class Doctor { ...@@ -269,10 +269,10 @@ class Doctor {
ValidationResult result; ValidationResult result;
try { try {
result = await validatorTask.result; result = await validatorTask.result;
} catch (exception, stackTrace) {
result = ValidationResult.crash(exception, stackTrace);
} finally {
status.stop(); status.stop();
} on Exception catch (exception, stackTrace) {
result = ValidationResult.crash(exception, stackTrace);
status.cancel();
} }
switch (result.type) { switch (result.type) {
...@@ -426,7 +426,7 @@ class GroupedValidator extends DoctorValidator { ...@@ -426,7 +426,7 @@ class GroupedValidator extends DoctorValidator {
_currentSlowWarning = subValidator.validator.slowWarning; _currentSlowWarning = subValidator.validator.slowWarning;
try { try {
results.add(await subValidator.result); results.add(await subValidator.result);
} catch (exception, stackTrace) { } on Exception catch (exception, stackTrace) {
results.add(ValidationResult.crash(exception, stackTrace)); results.add(ValidationResult.crash(exception, stackTrace));
} }
} }
...@@ -656,7 +656,7 @@ bool _genSnapshotRuns(String genSnapshotPath) { ...@@ -656,7 +656,7 @@ bool _genSnapshotRuns(String genSnapshotPath) {
const int kExpectedExitCode = 255; const int kExpectedExitCode = 255;
try { try {
return processUtils.runSync(<String>[genSnapshotPath]).exitCode == kExpectedExitCode; return processUtils.runSync(<String>[genSnapshotPath]).exitCode == kExpectedExitCode;
} catch (error) { } on Exception {
return false; return false;
} }
} }
...@@ -784,7 +784,7 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator { ...@@ -784,7 +784,7 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
String installPath; String installPath;
try { try {
installPath = globals.fs.file(globals.fs.path.join(dir.path, 'system', '.home')).readAsStringSync(); installPath = globals.fs.file(globals.fs.path.join(dir.path, 'system', '.home')).readAsStringSync();
} catch (e) { } on Exception {
// ignored // ignored
} }
if (installPath != null && globals.fs.isDirectorySync(installPath)) { if (installPath != null && globals.fs.isDirectorySync(installPath)) {
......
...@@ -271,7 +271,7 @@ class FuchsiaDevice extends Device { ...@@ -271,7 +271,7 @@ class FuchsiaDevice extends Device {
packageRepo.deleteSync(recursive: true); packageRepo.deleteSync(recursive: true);
} }
packageRepo.createSync(recursive: true); packageRepo.createSync(recursive: true);
} catch (e) { } on Exception catch (e) {
globals.printError('Failed to create Fuchisa package repo directory ' globals.printError('Failed to create Fuchisa package repo directory '
'at ${packageRepo.path}: $e'); 'at ${packageRepo.path}: $e');
return LaunchResult.failed(); return LaunchResult.failed();
...@@ -384,7 +384,7 @@ class FuchsiaDevice extends Device { ...@@ -384,7 +384,7 @@ class FuchsiaDevice extends Device {
globals.printTrace("Removing the tool's package repo: at ${packageRepo.path}"); globals.printTrace("Removing the tool's package repo: at ${packageRepo.path}");
try { try {
packageRepo.deleteSync(recursive: true); packageRepo.deleteSync(recursive: true);
} catch (e) { } on Exception catch (e) {
globals.printError('Failed to remove Fuchsia package repo directory ' globals.printError('Failed to remove Fuchsia package repo directory '
'at ${packageRepo.path}: $e.'); 'at ${packageRepo.path}: $e.');
} }
...@@ -467,9 +467,9 @@ class FuchsiaDevice extends Device { ...@@ -467,9 +467,9 @@ class FuchsiaDevice extends Device {
'Failed to delete screenshot.ppm from the device:\n$deleteResult' 'Failed to delete screenshot.ppm from the device:\n$deleteResult'
); );
} }
} catch (_) { } on Exception catch (e) {
globals.printError( globals.printError(
'Failed to delete screenshot.ppm from the device' 'Failed to delete screenshot.ppm from the device: $e'
); );
} }
} }
......
...@@ -92,7 +92,7 @@ class FuchsiaSdk { ...@@ -92,7 +92,7 @@ class FuchsiaSdk {
.transform(const LineSplitter())); .transform(const LineSplitter()));
}); });
return controller.stream; return controller.stream;
} catch (exception) { } on Exception catch (exception) {
globals.printTrace('$exception'); globals.printTrace('$exception');
} }
return const Stream<String>.empty(); return const Stream<String>.empty();
......
...@@ -67,7 +67,7 @@ class IntelliJPlugins { ...@@ -67,7 +67,7 @@ class IntelliJPlugins {
final int start = content.indexOf(versionStartTag); final int start = content.indexOf(versionStartTag);
final int end = content.indexOf('</version>', start); final int end = content.indexOf('</version>', start);
return content.substring(start + versionStartTag.length, end); return content.substring(start + versionStartTag.length, end);
} catch (_) { } on Exception {
return null; return null;
} }
} }
......
...@@ -448,7 +448,7 @@ String decodeSyslog(String line) { ...@@ -448,7 +448,7 @@ String decodeSyslog(String line) {
} }
} }
return utf8.decode(out); return utf8.decode(out);
} catch (_) { } on Exception {
// Unable to decode line: return as-is. // Unable to decode line: return as-is.
return line; return line;
} }
......
...@@ -291,7 +291,7 @@ class IOSSimulator extends Device { ...@@ -291,7 +291,7 @@ class IOSSimulator extends Device {
final IOSApp iosApp = app; final IOSApp iosApp = app;
await SimControl.instance.install(id, iosApp.simulatorBundlePath); await SimControl.instance.install(id, iosApp.simulatorBundlePath);
return true; return true;
} catch (e) { } on Exception {
return false; return false;
} }
} }
...@@ -301,7 +301,7 @@ class IOSSimulator extends Device { ...@@ -301,7 +301,7 @@ class IOSSimulator extends Device {
try { try {
await SimControl.instance.uninstall(id, app.id); await SimControl.instance.uninstall(id, app.id);
return true; return true;
} catch (e) { } on Exception {
return false; return false;
} }
} }
...@@ -395,7 +395,7 @@ class IOSSimulator extends Device { ...@@ -395,7 +395,7 @@ class IOSSimulator extends Device {
final String bundleIdentifier = globals.plistParser.getValueFromFile(plistPath, PlistParser.kCFBundleIdentifierKey); final String bundleIdentifier = globals.plistParser.getValueFromFile(plistPath, PlistParser.kCFBundleIdentifierKey);
await SimControl.instance.launch(id, bundleIdentifier, args); await SimControl.instance.launch(id, bundleIdentifier, args);
} catch (error) { } on Exception catch (error) {
globals.printError('$error'); globals.printError('$error');
return LaunchResult.failed(); return LaunchResult.failed();
} }
...@@ -411,7 +411,7 @@ class IOSSimulator extends Device { ...@@ -411,7 +411,7 @@ class IOSSimulator extends Device {
try { try {
final Uri deviceUri = await observatoryDiscovery.uri; final Uri deviceUri = await observatoryDiscovery.uri;
return LaunchResult.succeeded(observatoryUri: deviceUri); return LaunchResult.succeeded(observatoryUri: deviceUri);
} catch (error) { } on Exception catch (error) {
globals.printError('Error waiting for a debug connection: $error'); globals.printError('Error waiting for a debug connection: $error');
return LaunchResult.failed(); return LaunchResult.failed();
} finally { } finally {
......
...@@ -339,7 +339,7 @@ class XcodeProjectInterpreter { ...@@ -339,7 +339,7 @@ class XcodeProjectInterpreter {
); );
final String out = result.stdout.trim(); final String out = result.stdout.trim();
return parseXcodeBuildSettings(out); return parseXcodeBuildSettings(out);
} catch(error) { } on Exception catch (error) {
if (error is ProcessException && error.toString().contains('timed out')) { if (error is ProcessException && error.toString().contains('timed out')) {
BuildEvent('xcode-show-build-settings-timeout', BuildEvent('xcode-show-build-settings-timeout',
command: showBuildSettingsCommand.join(' '), command: showBuildSettingsCommand.join(' '),
......
...@@ -406,11 +406,15 @@ class XCDevice { ...@@ -406,11 +406,15 @@ class XCDevice {
final String architecture = deviceProperties['architecture'] as String; final String architecture = deviceProperties['architecture'] as String;
try { try {
cpuArchitecture = getIOSArchForName(architecture); cpuArchitecture = getIOSArchForName(architecture);
} catch (error) { } on Exception {
// Fallback to default iOS architecture. Future-proof against a theoretical version // Fallback to default iOS architecture. Future-proof against a
// of Xcode that changes this string to something slightly different like "ARM64". // theoretical version of Xcode that changes this string to something
// slightly different like "ARM64".
cpuArchitecture ??= defaultIOSArchs.first; cpuArchitecture ??= defaultIOSArchs.first;
_logger.printError('Unknown architecture $architecture, defaulting to ${getNameForDarwinArch(cpuArchitecture)}'); _logger.printError(
'Unknown architecture $architecture, defaulting to '
'${getNameForDarwinArch(cpuArchitecture)}',
);
} }
} }
return cpuArchitecture; return cpuArchitecture;
......
...@@ -126,7 +126,9 @@ class CrashReportSender { ...@@ -126,7 +126,9 @@ class CrashReportSender {
} else { } else {
globals.printError('Failed to send crash report. Server responded with HTTP status code ${resp.statusCode}'); globals.printError('Failed to send crash report. Server responded with HTTP status code ${resp.statusCode}');
} }
} catch (sendError, sendStackTrace) { // Catch all exceptions to print the message that makes clear that the
// crash logger crashed.
} catch (sendError, sendStackTrace) { // ignore: avoid_catches_without_on_clauses
if (sendError is SocketException || sendError is HttpException) { if (sendError is SocketException || sendError is HttpException) {
globals.printError('Failed to send crash report due to a network error: $sendError'); globals.printError('Failed to send crash report due to a network error: $sendError');
} else { } else {
......
...@@ -195,7 +195,7 @@ class CommandResultEvent extends UsageEvent { ...@@ -195,7 +195,7 @@ class CommandResultEvent extends UsageEvent {
label: parameter, label: parameter,
value: maxRss, value: maxRss,
); );
} catch (error) { } on Exception catch (error) {
// If grabbing the maxRss fails for some reason, just don't send an event. // If grabbing the maxRss fails for some reason, just don't send an event.
globals.printTrace('Querying maxRss failed with error: $error'); globals.printTrace('Querying maxRss failed with error: $error');
} }
......
...@@ -136,7 +136,7 @@ ${_projectMetadataInformation()} ...@@ -136,7 +136,7 @@ ${_projectMetadataInformation()}
} else { } else {
globals.printTrace('Failed to shorten GitHub template URL. Server responded with HTTP status code ${response.statusCode}'); globals.printTrace('Failed to shorten GitHub template URL. Server responded with HTTP status code ${response.statusCode}');
} }
} catch (sendError) { } on Exception catch (sendError) {
globals.printTrace('Failed to shorten GitHub template URL: $sendError'); globals.printTrace('Failed to shorten GitHub template URL: $sendError');
} }
......
...@@ -873,7 +873,7 @@ abstract class ResidentRunner { ...@@ -873,7 +873,7 @@ abstract class ResidentRunner {
for (final FlutterView view in device.views) { for (final FlutterView view in device.views) {
await view.uiIsolate.flutterDebugAllowBanner(false); await view.uiIsolate.flutterDebugAllowBanner(false);
} }
} catch (error) { } on Exception catch (error) {
status.cancel(); status.cancel();
globals.printError('Error communicating with Flutter on the device: $error'); globals.printError('Error communicating with Flutter on the device: $error');
return; return;
...@@ -887,7 +887,7 @@ abstract class ResidentRunner { ...@@ -887,7 +887,7 @@ abstract class ResidentRunner {
for (final FlutterView view in device.views) { for (final FlutterView view in device.views) {
await view.uiIsolate.flutterDebugAllowBanner(true); await view.uiIsolate.flutterDebugAllowBanner(true);
} }
} catch (error) { } on Exception catch (error) {
status.cancel(); status.cancel();
globals.printError('Error communicating with Flutter on the device: $error'); globals.printError('Error communicating with Flutter on the device: $error');
return; return;
...@@ -899,7 +899,7 @@ abstract class ResidentRunner { ...@@ -899,7 +899,7 @@ abstract class ResidentRunner {
globals.printStatus( globals.printStatus(
'Screenshot written to ${globals.fs.path.relative(outputFile.path)} (${sizeKB}kB).', 'Screenshot written to ${globals.fs.path.relative(outputFile.path)} (${sizeKB}kB).',
); );
} catch (error) { } on Exception catch (error) {
status.cancel(); status.cancel();
globals.printError('Error taking screenshot: $error'); globals.printError('Error taking screenshot: $error');
} }
...@@ -1301,7 +1301,8 @@ class TerminalHandler { ...@@ -1301,7 +1301,8 @@ class TerminalHandler {
try { try {
lastReceivedCommand = command; lastReceivedCommand = command;
await _commonTerminalInputHandler(command); await _commonTerminalInputHandler(command);
} catch (error, st) { // Catch all exception since this is doing cleanup and rethrowing.
} catch (error, st) { // ignore: avoid_catches_without_on_clauses
// Don't print stack traces for known error types. // Don't print stack traces for known error types.
if (error is! ToolExit) { if (error is! ToolExit) {
globals.printError('$error\n$st'); globals.printError('$error\n$st');
......
...@@ -131,7 +131,7 @@ class ColdRunner extends ResidentRunner { ...@@ -131,7 +131,7 @@ class ColdRunner extends ResidentRunner {
_didAttach = true; _didAttach = true;
try { try {
await connectToServiceProtocol(); await connectToServiceProtocol();
} catch (error) { } on Exception catch (error) {
globals.printError('Error connecting to the service protocol: $error'); globals.printError('Error connecting to the service protocol: $error');
// https://github.com/flutter/flutter/issues/33050 // https://github.com/flutter/flutter/issues/33050
// TODO(blasten): Remove this check once https://issuetracker.google.com/issues/132325318 has been fixed. // TODO(blasten): Remove this check once https://issuetracker.google.com/issues/132325318 has been fixed.
......
...@@ -186,7 +186,7 @@ class HotRunner extends ResidentRunner { ...@@ -186,7 +186,7 @@ class HotRunner extends ResidentRunner {
final Map<String, dynamic> firstReport = reports.first; final Map<String, dynamic> firstReport = reports.first;
await device.updateReloadStatus(validateReloadReport(firstReport, printErrors: false)); await device.updateReloadStatus(validateReloadReport(firstReport, printErrors: false));
} }
} catch (error) { } on Exception catch (error) {
return OperationResult(1, error.toString()); return OperationResult(1, error.toString());
} }
...@@ -215,14 +215,25 @@ class HotRunner extends ResidentRunner { ...@@ -215,14 +215,25 @@ class HotRunner extends ResidentRunner {
compileExpression: _compileExpressionService, compileExpression: _compileExpressionService,
reloadMethod: reloadMethod, reloadMethod: reloadMethod,
); );
} catch (error) { // Catches all exceptions, non-Exception objects are rethrown.
} catch (error) { // ignore: avoid_catches_without_on_clauses
if (error is! Exception && error is! String) {
rethrow;
}
globals.printError('Error connecting to the service protocol: $error'); globals.printError('Error connecting to the service protocol: $error');
// https://github.com/flutter/flutter/issues/33050 // https://github.com/flutter/flutter/issues/33050
// TODO(blasten): Remove this check once https://issuetracker.google.com/issues/132325318 has been fixed. // TODO(blasten): Remove this check once
// https://issuetracker.google.com/issues/132325318 has been fixed.
if (await hasDeviceRunningAndroidQ(flutterDevices) && if (await hasDeviceRunningAndroidQ(flutterDevices) &&
error.toString().contains(kAndroidQHttpConnectionClosedExp)) { error.toString().contains(kAndroidQHttpConnectionClosedExp)) {
globals.printStatus('🔨 If you are using an emulator running Android Q Beta, consider using an emulator running API level 29 or lower.'); globals.printStatus(
globals.printStatus('Learn more about the status of this issue on https://issuetracker.google.com/issues/132325318.'); '🔨 If you are using an emulator running Android Q Beta, '
'consider using an emulator running API level 29 or lower.',
);
globals.printStatus(
'Learn more about the status of this issue on '
'https://issuetracker.google.com/issues/132325318.',
);
} }
return 2; return 2;
} }
...@@ -242,7 +253,7 @@ class HotRunner extends ResidentRunner { ...@@ -242,7 +253,7 @@ class HotRunner extends ResidentRunner {
), ),
); );
} }
} catch (error) { } on Exception catch (error) {
globals.printError('Error initializing DevFS: $error'); globals.printError('Error initializing DevFS: $error');
return 3; return 3;
} }
...@@ -872,7 +883,7 @@ class HotRunner extends ResidentRunner { ...@@ -872,7 +883,7 @@ class HotRunner extends ResidentRunner {
return OperationResult(errorCode, errorMessage); return OperationResult(errorCode, errorMessage);
} }
return OperationResult(errorCode, '$errorMessage (error code: $errorCode)'); return OperationResult(errorCode, '$errorMessage (error code: $errorCode)');
} catch (error, stackTrace) { } on Exception catch (error, stackTrace) {
globals.printTrace('Hot reload failed: $error\n$stackTrace'); globals.printTrace('Hot reload failed: $error\n$stackTrace');
return OperationResult(1, '$error'); return OperationResult(1, '$error');
} }
...@@ -936,7 +947,7 @@ class HotRunner extends ResidentRunner { ...@@ -936,7 +947,7 @@ class HotRunner extends ResidentRunner {
() async { () async {
try { try {
await view.uiIsolate.flutterReassemble(); await view.uiIsolate.flutterReassemble();
} catch (error) { } on Exception catch (error) {
failedReassemble = true; failedReassemble = true;
globals.printError('Reassembling ${view.uiIsolate.name} failed: $error'); globals.printError('Reassembling ${view.uiIsolate.name} failed: $error');
return; return;
......
...@@ -8,6 +8,7 @@ import 'package:args/args.dart'; ...@@ -8,6 +8,7 @@ import 'package:args/args.dart';
import 'package:args/command_runner.dart'; import 'package:args/command_runner.dart';
import 'package:completion/completion.dart'; import 'package:completion/completion.dart';
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:meta/meta.dart';
import '../artifacts.dart'; import '../artifacts.dart';
import '../base/common.dart'; import '../base/common.dart';
...@@ -189,7 +190,7 @@ class FlutterCommandRunner extends CommandRunner<void> { ...@@ -189,7 +190,7 @@ class FlutterCommandRunner extends CommandRunner<void> {
if (script.contains('flutter/examples/')) { if (script.contains('flutter/examples/')) {
return script.substring(0, script.indexOf('flutter/examples/') + 8); return script.substring(0, script.indexOf('flutter/examples/') + 8);
} }
} catch (error) { } on Exception catch (error) {
// we don't have a logger at the time this is run // we don't have a logger at the time this is run
// (which is why we don't use printTrace here) // (which is why we don't use printTrace here)
print(userMessages.runnerNoRoot('$error')); print(userMessages.runnerNoRoot('$error'));
...@@ -421,6 +422,7 @@ class FlutterCommandRunner extends CommandRunner<void> { ...@@ -421,6 +422,7 @@ class FlutterCommandRunner extends CommandRunner<void> {
return EngineBuildPaths(targetEngine: engineBuildPath, hostEngine: engineHostBuildPath); return EngineBuildPaths(targetEngine: engineBuildPath, hostEngine: engineHostBuildPath);
} }
@visibleForTesting
static void initFlutterRoot() { static void initFlutterRoot() {
Cache.flutterRoot ??= defaultFlutterRoot; Cache.flutterRoot ??= defaultFlutterRoot;
} }
......
...@@ -313,7 +313,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -313,7 +313,7 @@ class FlutterPlatform extends PlatformPlugin {
final RunnerSuiteController controller = deserializeSuite(path, platform, final RunnerSuiteController controller = deserializeSuite(path, platform,
suiteConfig, const PluginEnvironment(), channel, message); suiteConfig, const PluginEnvironment(), channel, message);
return await controller.suite; return await controller.suite;
} catch (err) { } on Exception catch (err) {
/// Rethrow a less confusing error if it is a test incompatibility. /// Rethrow a less confusing error if it is a test incompatibility.
if (err.toString().contains("type 'Declarer' is not a subtype of type 'Declarer'")) { if (err.toString().contains("type 'Declarer' is not a subtype of type 'Declarer'")) {
throw UnsupportedError('Package incompatibility between flutter and test packages:\n' throw UnsupportedError('Package incompatibility between flutter and test packages:\n'
...@@ -667,7 +667,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -667,7 +667,7 @@ class FlutterPlatform extends PlatformPlugin {
} }
break; break;
} }
} catch (error, stack) { } on Exception catch (error, stack) {
globals.printTrace('test $ourTestCount: error caught during test; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); globals.printTrace('test $ourTestCount: error caught during test; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}');
if (!controllerSinkClosed) { if (!controllerSinkClosed) {
controller.sink.addError(error, stack); controller.sink.addError(error, stack);
...@@ -681,7 +681,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -681,7 +681,7 @@ class FlutterPlatform extends PlatformPlugin {
for (final Finalizer finalizer in finalizers.reversed) { for (final Finalizer finalizer in finalizers.reversed) {
try { try {
await finalizer(); await finalizer();
} catch (error, stack) { } on Exception catch (error, stack) {
globals.printTrace('test $ourTestCount: error while cleaning up; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); globals.printTrace('test $ourTestCount: error while cleaning up; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}');
if (!controllerSinkClosed) { if (!controllerSinkClosed) {
controller.sink.addError(error, stack); controller.sink.addError(error, stack);
...@@ -873,7 +873,7 @@ class FlutterPlatform extends PlatformPlugin { ...@@ -873,7 +873,7 @@ class FlutterPlatform extends PlatformPlugin {
if (reportObservatoryUri != null) { if (reportObservatoryUri != null) {
reportObservatoryUri(uri); reportObservatoryUri(uri);
} }
} catch (error) { } on Exception catch (error) {
globals.printError('Could not parse shell observatory port message: $error'); globals.printError('Could not parse shell observatory port message: $error');
} }
} else if (line != null) { } else if (line != null) {
......
...@@ -735,7 +735,8 @@ class BrowserManager { ...@@ -735,7 +735,8 @@ class BrowserManager {
_controllers.add(controller); _controllers.add(controller);
return await controller.suite; return await controller.suite;
} catch (_) { // Not limiting to catching Exception because the exception is rethrown.
} catch (_) { // ignore: avoid_catches_without_on_clauses
closeIframe(); closeIframe();
rethrow; rethrow;
} }
...@@ -989,7 +990,7 @@ void main() async { ...@@ -989,7 +990,7 @@ void main() async {
try { try {
bool success = await goldenFileComparator.compare(bytes, goldenKey); bool success = await goldenFileComparator.compare(bytes, goldenKey);
print(jsonEncode({'success': success})); print(jsonEncode({'success': success}));
} catch (ex) { } on Exception catch (ex) {
print(jsonEncode({'success': false, 'message': '\$ex'})); print(jsonEncode({'success': false, 'message': '\$ex'}));
} }
} }
......
...@@ -194,7 +194,7 @@ class FlutterTesterDevice extends Device { ...@@ -194,7 +194,7 @@ class FlutterTesterDevice extends Device {
final Uri observatoryUri = await observatoryDiscovery.uri; final Uri observatoryUri = await observatoryDiscovery.uri;
return LaunchResult.succeeded(observatoryUri: observatoryUri); return LaunchResult.succeeded(observatoryUri: observatoryUri);
} catch (error) { } on Exception catch (error) {
globals.printError('Failed to launch $package: $error'); globals.printError('Failed to launch $package: $error');
return LaunchResult.failed(); return LaunchResult.failed();
} }
......
...@@ -60,7 +60,8 @@ class Tracing { ...@@ -60,7 +60,8 @@ class Tracing {
if (!done) { if (!done) {
await whenFirstFrameRendered.future; await whenFirstFrameRendered.future;
} }
} catch (exception) { // The exception is rethrown, so don't catch only Exceptions.
} catch (exception) { // ignore: avoid_catches_without_on_clauses
status.cancel(); status.cancel();
rethrow; rethrow;
} }
......
...@@ -528,7 +528,7 @@ class VersionCheckStamp { ...@@ -528,7 +528,7 @@ class VersionCheckStamp {
} else { } else {
globals.printTrace('Warning: expected version stamp to be a Map but found: $jsonObject'); globals.printTrace('Warning: expected version stamp to be a Map but found: $jsonObject');
} }
} catch (error, stackTrace) { } on Exception catch (error, stackTrace) {
// Do not crash if JSON is malformed. // Do not crash if JSON is malformed.
globals.printTrace('${error.runtimeType}: $error\n$stackTrace'); globals.printTrace('${error.runtimeType}: $error\n$stackTrace');
} }
......
...@@ -145,7 +145,7 @@ class VMService { ...@@ -145,7 +145,7 @@ class VMService {
return <String, String>{'type': 'Success'}; return <String, String>{'type': 'Success'};
} on rpc.RpcException { } on rpc.RpcException {
rethrow; rethrow;
} catch (e, st) { } on Exception catch (e, st) {
throw rpc.RpcException(rpc_error_code.SERVER_ERROR, throw rpc.RpcException(rpc_error_code.SERVER_ERROR,
'Error during Sources Reload: $e\n$st'); 'Error during Sources Reload: $e\n$st');
} }
...@@ -189,7 +189,7 @@ class VMService { ...@@ -189,7 +189,7 @@ class VMService {
return <String, String>{'type': 'Success'}; return <String, String>{'type': 'Success'};
} on rpc.RpcException { } on rpc.RpcException {
rethrow; rethrow;
} catch (e, st) { } on Exception catch (e, st) {
throw rpc.RpcException(rpc_error_code.SERVER_ERROR, throw rpc.RpcException(rpc_error_code.SERVER_ERROR,
'Error during Sources Reload: $e\n$st'); 'Error during Sources Reload: $e\n$st');
} }
...@@ -213,7 +213,7 @@ class VMService { ...@@ -213,7 +213,7 @@ class VMService {
return <String, String>{'type': 'Success'}; return <String, String>{'type': 'Success'};
} on rpc.RpcException { } on rpc.RpcException {
rethrow; rethrow;
} catch (e, st) { } on Exception catch (e, st) {
throw rpc.RpcException(rpc_error_code.SERVER_ERROR, throw rpc.RpcException(rpc_error_code.SERVER_ERROR,
'Error during Hot Restart: $e\n$st'); 'Error during Hot Restart: $e\n$st');
} }
...@@ -266,7 +266,7 @@ class VMService { ...@@ -266,7 +266,7 @@ class VMService {
'result': <String, dynamic> {'kernelBytes': kernelBytesBase64}}; 'result': <String, dynamic> {'kernelBytes': kernelBytesBase64}};
} on rpc.RpcException { } on rpc.RpcException {
rethrow; rethrow;
} catch (e, st) { } on Exception catch (e, st) {
throw rpc.RpcException(rpc_error_code.SERVER_ERROR, throw rpc.RpcException(rpc_error_code.SERVER_ERROR,
'Error during expression compilation: $e\n$st'); 'Error during expression compilation: $e\n$st');
} }
...@@ -625,7 +625,8 @@ abstract class ServiceObject { ...@@ -625,7 +625,8 @@ abstract class ServiceObject {
updateFromMap(response); updateFromMap(response);
completer.complete(this); completer.complete(this);
} }
} catch (e, st) { // Catches all exceptions to propagate to the completer.
} catch (e, st) { // ignore: avoid_catches_without_on_clauses
completer.completeError(e, st); completer.completeError(e, st);
} }
_inProgressReload = null; _inProgressReload = null;
......
...@@ -211,7 +211,7 @@ class ChromeLauncher { ...@@ -211,7 +211,7 @@ class ChromeLauncher {
if (!skipCheck) { if (!skipCheck) {
try { try {
await chrome.chromeConnection.getTabs(); await chrome.chromeConnection.getTabs();
} catch (e) { } on Exception catch (e) {
await chrome.close(); await chrome.close();
throwToolExit( throwToolExit(
'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $e'); 'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $e');
...@@ -235,7 +235,7 @@ class ChromeLauncher { ...@@ -235,7 +235,7 @@ class ChromeLauncher {
final HttpClientResponse response = await request.close(); final HttpClientResponse response = await request.close();
final List<dynamic> jsonObject = await json.fuse(utf8).decoder.bind(response).single as List<dynamic>; final List<dynamic> jsonObject = await json.fuse(utf8).decoder.bind(response).single as List<dynamic>;
return base.resolve(jsonObject.first['devtoolsFrontendUrl'] as String); return base.resolve(jsonObject.first['devtoolsFrontendUrl'] as String);
} catch (_) { } on Exception {
// If we fail to talk to the remote debugger protocol, give up and return // If we fail to talk to the remote debugger protocol, give up and return
// the raw URL rather than crashing. // the raw URL rather than crashing.
return base; return base;
......
...@@ -66,7 +66,7 @@ Future<void> buildWeb( ...@@ -66,7 +66,7 @@ Future<void> buildWeb(
} }
throwToolExit('Failed to compile application for the Web.'); throwToolExit('Failed to compile application for the Web.');
} }
} catch (err) { } on Exception catch (err) {
throwToolExit(err.toString()); throwToolExit(err.toString());
} finally { } finally {
status.stop(); status.stop();
......
...@@ -7,6 +7,7 @@ import 'package:flutter_tools/src/base/file_system.dart'; ...@@ -7,6 +7,7 @@ import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/assemble.dart'; import 'package:flutter_tools/src/commands/assemble.dart';
import 'package:flutter_tools/src/runner/flutter_command_runner.dart';
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/globals.dart' as globals;
...@@ -15,6 +16,7 @@ import '../../src/context.dart'; ...@@ -15,6 +16,7 @@ import '../../src/context.dart';
import '../../src/testbed.dart'; import '../../src/testbed.dart';
void main() { void main() {
FlutterCommandRunner.initFlutterRoot();
Cache.disableLocking(); Cache.disableLocking();
final Testbed testbed = Testbed(overrides: <Type, Generator>{ final Testbed testbed = Testbed(overrides: <Type, Generator>{
BuildSystem: () => MockBuildSystem(), BuildSystem: () => MockBuildSystem(),
......
...@@ -76,7 +76,7 @@ void main() { ...@@ -76,7 +76,7 @@ void main() {
'--show-test-device', '--show-test-device',
]); ]);
fail('Expect exception'); fail('Expect exception');
} catch (e) { } on Exception catch (e) {
expect(e.toString(), isNot(contains('--fast-start is not supported with --use-application-binary'))); expect(e.toString(), isNot(contains('--fast-start is not supported with --use-application-binary')));
} }
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
...@@ -102,7 +102,7 @@ void main() { ...@@ -102,7 +102,7 @@ void main() {
'--no-pub', '--no-pub',
]); ]);
fail('Expect exception'); fail('Expect exception');
} catch (e) { } on Exception catch (e) {
expect(e, isInstanceOf<ToolExit>()); expect(e, isInstanceOf<ToolExit>());
} }
final BufferLogger bufferLogger = globals.logger as BufferLogger; final BufferLogger bufferLogger = globals.logger as BufferLogger;
...@@ -127,7 +127,7 @@ void main() { ...@@ -127,7 +127,7 @@ void main() {
'--no-pub', '--no-pub',
]); ]);
fail('Expect exception'); fail('Expect exception');
} catch (e) { } on Exception catch (e) {
expect(e, isInstanceOf<ToolExit>()); expect(e, isInstanceOf<ToolExit>());
expect(e.toString(), contains('No pubspec.yaml file found')); expect(e.toString(), contains('No pubspec.yaml file found'));
} }
...@@ -221,8 +221,8 @@ void main() { ...@@ -221,8 +221,8 @@ void main() {
} on ToolExit catch (e) { } on ToolExit catch (e) {
// We expect a ToolExit because no devices are attached // We expect a ToolExit because no devices are attached
expect(e.message, null); expect(e.message, null);
} catch (e) { } on Exception catch (e) {
fail('ToolExit expected'); fail('ToolExit expected, got $e');
} }
verifyInOrder(<void>[ verifyInOrder(<void>[
...@@ -293,8 +293,8 @@ void main() { ...@@ -293,8 +293,8 @@ void main() {
} on ToolExit catch (e) { } on ToolExit catch (e) {
// We expect a ToolExit because app does not start // We expect a ToolExit because app does not start
expect(e.message, null); expect(e.message, null);
} catch (e) { } on Exception catch (e) {
fail('ToolExit expected'); fail('ToolExit expected, got $e');
} }
final List<dynamic> captures = verify(mockUsage.sendCommand( final List<dynamic> captures = verify(mockUsage.sendCommand(
captureAny, captureAny,
......
...@@ -163,7 +163,7 @@ void main() { ...@@ -163,7 +163,7 @@ void main() {
try { try {
await command.getTags(); await command.getTags();
fail('ToolExit expected'); fail('ToolExit expected');
} catch(e) { } on Exception catch (e) {
expect(e, isA<ToolExit>()); expect(e, isA<ToolExit>());
} }
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
......
...@@ -584,7 +584,9 @@ flutter: ...@@ -584,7 +584,9 @@ flutter:
final AndroidDevice device = AndroidDevice('emulator-5555'); final AndroidDevice device = AndroidDevice('emulator-5555');
expect(await device.emulatorId, isNull); expect(await device.emulatorId, isNull);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
AndroidConsoleSocketFactory: () => (String host, int port) => throw 'Fake socket error', AndroidConsoleSocketFactory: () {
return (String host, int port) => throw Exception('Fake socket error');
},
ProcessManager: () => mockProcessManager, ProcessManager: () => mockProcessManager,
}); });
......
...@@ -80,6 +80,13 @@ void main() { ...@@ -80,6 +80,13 @@ void main() {
when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'], when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'],
environment: argThat(isNotNull, named: 'environment'))) environment: argThat(isNotNull, named: 'environment')))
.thenReturn(ProcessResult(1, 0, '26.1.1\n', '')); .thenReturn(ProcessResult(1, 0, '26.1.1\n', ''));
if (globals.platform.isMacOS) {
when(globals.processManager.runSync(
<String>['/usr/libexec/java_home'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
}
expect(sdk.sdkManagerVersion, '26.1.1'); expect(sdk.sdkManagerVersion, '26.1.1');
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FileSystem: () => fs, FileSystem: () => fs,
...@@ -112,6 +119,13 @@ void main() { ...@@ -112,6 +119,13 @@ void main() {
when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'], when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'],
environment: argThat(isNotNull, named: 'environment'))) environment: argThat(isNotNull, named: 'environment')))
.thenReturn(ProcessResult(1, 1, '26.1.1\n', 'Mystery error')); .thenReturn(ProcessResult(1, 1, '26.1.1\n', 'Mystery error'));
if (globals.platform.isMacOS) {
when(globals.processManager.runSync(
<String>['/usr/libexec/java_home'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
}
expect(sdk.sdkManagerVersion, isNull); expect(sdk.sdkManagerVersion, isNull);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FileSystem: () => fs, FileSystem: () => fs,
......
...@@ -70,26 +70,32 @@ $assetsSection ...@@ -70,26 +70,32 @@ $assetsSection
Future<void> buildAndVerifyAssets( Future<void> buildAndVerifyAssets(
List<String> assets, List<String> assets,
List<String> packages, List<String> packages,
String expectedAssetManifest, String expectedAssetManifest, {
) async { bool expectExists = true,
}) async {
final AssetBundle bundle = AssetBundleFactory.instance.createBundle(); final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(manifestPath: 'pubspec.yaml'); await bundle.build(manifestPath: 'pubspec.yaml');
for (final String packageName in packages) { for (final String packageName in packages) {
for (final String asset in assets) { for (final String asset in assets) {
final String entryKey = Uri.encodeFull('packages/$packageName/$asset'); final String entryKey = Uri.encodeFull('packages/$packageName/$asset');
expect(bundle.entries.containsKey(entryKey), true, reason: 'Cannot find key on bundle: $entryKey'); expect(bundle.entries.containsKey(entryKey), expectExists,
expect( reason: 'Cannot find key on bundle: $entryKey');
utf8.decode(await bundle.entries[entryKey].contentsAsBytes()), if (expectExists) {
asset, expect(
); utf8.decode(await bundle.entries[entryKey].contentsAsBytes()),
asset,
);
}
} }
} }
expect( if (expectExists) {
utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()), expect(
expectedAssetManifest, utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()),
); expectedAssetManifest,
);
}
} }
void writeAssets(String path, List<String> assets) { void writeAssets(String path, List<String> assets) {
...@@ -660,24 +666,15 @@ $assetsSection ...@@ -660,24 +666,15 @@ $assetsSection
assets: assetOnManifest, assets: assetOnManifest,
); );
try { await buildAndVerifyAssets(
await buildAndVerifyAssets( assetOnManifest,
assetOnManifest, <String>['test_package'],
<String>['test_package'], null,
null, expectExists: false,
); );
final Function watchdog = () async {
assert(false, 'Code failed to detect missing directory. Test failed.');
};
watchdog();
} catch (e) {
// Test successful
}
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FileSystem: () => testFileSystem, FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(), ProcessManager: () => FakeProcessManager.any(),
}); });
}); });
} }
...@@ -197,7 +197,7 @@ void main() { ...@@ -197,7 +197,7 @@ void main() {
); );
try { try {
await f; await f;
} catch (e) { } on String {
caughtByHandler = true; caughtByHandler = true;
} }
if (!completer.isCompleted) { if (!completer.isCompleted) {
...@@ -235,7 +235,7 @@ void main() { ...@@ -235,7 +235,7 @@ void main() {
); );
try { try {
await f; await f;
} catch (e) { } on String {
caughtByHandler = true; caughtByHandler = true;
} }
if (!completer.isCompleted) { if (!completer.isCompleted) {
...@@ -275,7 +275,7 @@ void main() { ...@@ -275,7 +275,7 @@ void main() {
); );
try { try {
await f; await f;
} catch (e) { } on String {
caughtByHandler = true; caughtByHandler = true;
} }
if (!completer.isCompleted) { if (!completer.isCompleted) {
......
...@@ -249,7 +249,7 @@ void main() { ...@@ -249,7 +249,7 @@ void main() {
globals.fs.file('a.dart').createSync(); globals.fs.file('a.dart').createSync();
expect( expect(
() => Fingerprint.fromBuildInputs(<String, String>{}, <String>['a.dart', 'b.dart']), () => Fingerprint.fromBuildInputs(<String, String>{}, <String>['a.dart', 'b.dart']),
throwsArgumentError, throwsException,
); );
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FileSystem: () => fs, FileSystem: () => fs,
...@@ -328,7 +328,7 @@ void main() { ...@@ -328,7 +328,7 @@ void main() {
'properties': <String, String>{}, 'properties': <String, String>{},
'files': <String, String>{}, 'files': <String, String>{},
}); });
expect(() => Fingerprint.fromJson(jsonString), throwsArgumentError); expect(() => Fingerprint.fromJson(jsonString), throwsException);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FlutterVersion: () => mockVersion, FlutterVersion: () => mockVersion,
}); });
...@@ -338,7 +338,7 @@ void main() { ...@@ -338,7 +338,7 @@ void main() {
'properties': <String, String>{}, 'properties': <String, String>{},
'files': <String, String>{}, 'files': <String, String>{},
}); });
expect(() => Fingerprint.fromJson(jsonString), throwsArgumentError); expect(() => Fingerprint.fromJson(jsonString), throwsException);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FlutterVersion: () => mockVersion, FlutterVersion: () => mockVersion,
}); });
......
...@@ -61,8 +61,9 @@ void main() { ...@@ -61,8 +61,9 @@ void main() {
}); });
testUsingContext('signal handler error goes on error stream', () async { testUsingContext('signal handler error goes on error stream', () async {
final Exception exn = Exception('Error');
signals.addHandler(signalUnderTest, (ProcessSignal s) { signals.addHandler(signalUnderTest, (ProcessSignal s) {
throw 'Error'; throw exn;
}); });
final Completer<void> completer = Completer<void>(); final Completer<void> completer = Completer<void>();
...@@ -75,7 +76,7 @@ void main() { ...@@ -75,7 +76,7 @@ void main() {
controller.add(mockSignal); controller.add(mockSignal);
await completer.future; await completer.future;
await errSub.cancel(); await errSub.cancel();
expect(errList, <Object>['Error']); expect(errList, contains(exn));
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
Signals: () => Signals(), Signals: () => Signals(),
}); });
......
...@@ -91,6 +91,6 @@ void main() { ...@@ -91,6 +91,6 @@ void main() {
expect(getIOSArchForName('arm64'), DarwinArch.arm64); expect(getIOSArchForName('arm64'), DarwinArch.arm64);
expect(getIOSArchForName('arm64e'), DarwinArch.arm64); expect(getIOSArchForName('arm64e'), DarwinArch.arm64);
expect(getIOSArchForName('x86_64'), DarwinArch.x86_64); expect(getIOSArchForName('x86_64'), DarwinArch.x86_64);
expect(() => getIOSArchForName('bogus'), throwsAssertionError); expect(() => getIOSArchForName('bogus'), throwsException);
}); });
} }
...@@ -231,7 +231,7 @@ void main() { ...@@ -231,7 +231,7 @@ void main() {
null, null,
}); });
fail('Mock thrown exception expected'); fail('Mock thrown exception expected');
} catch (e) { } on Exception {
verify(artifact1.update()); verify(artifact1.update());
// Don't continue when retrieval fails. // Don't continue when retrieval fails.
verifyNever(artifact2.update()); verifyNever(artifact2.update());
......
...@@ -152,6 +152,26 @@ void main() { ...@@ -152,6 +152,26 @@ void main() {
.thenAnswer((_) => Future<Process>.value(process)); .thenAnswer((_) => Future<Process>.value(process));
when(mockProcessManager.canRun(any)).thenReturn(false); when(mockProcessManager.canRun(any)).thenReturn(false);
when(mockProcessManager.runSync(
argThat(contains(contains('gen_snapshot'))),
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 255, '', ''));
when(mockProcessManager.runSync(
<String>['/usr/bin/xcode-select', '--print-path'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
when(mockProcessManager.run(
<String>['which', 'pod'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenAnswer((_) {
return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
});
mockAndroidSdk = MockAndroidSdk(); mockAndroidSdk = MockAndroidSdk();
when(mockAndroidSdk.directory).thenReturn('irrelevant'); when(mockAndroidSdk.directory).thenReturn('irrelevant');
}); });
......
...@@ -9,12 +9,11 @@ import 'package:flutter_tools/src/android/android_builder.dart'; ...@@ -9,12 +9,11 @@ import 'package:flutter_tools/src/android/android_builder.dart';
import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_appbundle.dart'; import 'package:flutter_tools/src/commands/build_appbundle.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'package:process/process.dart'; import 'package:process/process.dart';
...@@ -135,6 +134,26 @@ void main() { ...@@ -135,6 +134,26 @@ void main() {
.thenAnswer((_) => Future<Process>.value(process)); .thenAnswer((_) => Future<Process>.value(process));
when(mockProcessManager.canRun(any)).thenReturn(false); when(mockProcessManager.canRun(any)).thenReturn(false);
when(mockProcessManager.runSync(
argThat(contains(contains('gen_snapshot'))),
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 255, '', ''));
when(mockProcessManager.runSync(
<String>['/usr/bin/xcode-select', '--print-path'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
when(mockProcessManager.run(
<String>['which', 'pod'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenAnswer((_) {
return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
});
mockAndroidSdk = MockAndroidSdk(); mockAndroidSdk = MockAndroidSdk();
when(mockAndroidSdk.validateSdkWellFormed()).thenReturn(const <String>[]); when(mockAndroidSdk.validateSdkWellFormed()).thenReturn(const <String>[]);
when(mockAndroidSdk.directory).thenReturn('irrelevant'); when(mockAndroidSdk.directory).thenReturn('irrelevant');
......
...@@ -327,8 +327,7 @@ void main() { ...@@ -327,8 +327,7 @@ void main() {
try { try {
await pub.get(context: PubContext.flutterTests, checkLastModified: true); await pub.get(context: PubContext.flutterTests, checkLastModified: true);
expect(true, isFalse, reason: 'pub.get did not throw'); expect(true, isFalse, reason: 'pub.get did not throw');
} catch (error) { } on ToolExit catch (error) {
expect(error, isA<Exception>());
expect(error.message, '/: unexpected concurrent modification of pubspec.yaml while running pub.'); expect(error.message, '/: unexpected concurrent modification of pubspec.yaml while running pub.');
} }
expect(testLogger.statusText, 'Running "flutter pub get" in /...\n'); expect(testLogger.statusText, 'Running "flutter pub get" in /...\n');
......
...@@ -136,7 +136,7 @@ void main() { ...@@ -136,7 +136,7 @@ void main() {
const int kFailedAttempts = 5; const int kFailedAttempts = 5;
when(httpRequest.close()).thenAnswer((Invocation invocation) { when(httpRequest.close()).thenAnswer((Invocation invocation) {
if (nRequest++ < kFailedAttempts) { if (nRequest++ < kFailedAttempts) {
throw 'Connection resert by peer'; throw Exception('Connection resert by peer');
} }
return Future<HttpClientResponse>.value(httpClientResponse); return Future<HttpClientResponse>.value(httpClientResponse);
}); });
......
...@@ -46,8 +46,17 @@ void main() { ...@@ -46,8 +46,17 @@ void main() {
Future<Map<String, String>> captureEnvironment() async { Future<Map<String, String>> captureEnvironment() async {
flutterPlatform.loadChannel('test1.dart', MockSuitePlatform()); flutterPlatform.loadChannel('test1.dart', MockSuitePlatform());
when(mockProcessManager.start(
any,
environment: anyNamed('environment')),
).thenAnswer((_) {
return Future<Process>.value(MockProcess());
});
await untilCalled(mockProcessManager.start(any, environment: anyNamed('environment'))); await untilCalled(mockProcessManager.start(any, environment: anyNamed('environment')));
final VerificationResult toVerify = verify(mockProcessManager.start(any, environment: captureAnyNamed('environment'))); final VerificationResult toVerify = verify(mockProcessManager.start(
any,
environment: captureAnyNamed('environment'),
));
expect(toVerify.captured, hasLength(1)); expect(toVerify.captured, hasLength(1));
expect(toVerify.captured.first, isA<Map<String, String>>()); expect(toVerify.captured.first, isA<Map<String, String>>());
return toVerify.captured.first as Map<String, String>; return toVerify.captured.first as Map<String, String>;
...@@ -146,6 +155,8 @@ class MockSuitePlatform extends Mock implements SuitePlatform {} ...@@ -146,6 +155,8 @@ class MockSuitePlatform extends Mock implements SuitePlatform {}
class MockProcessManager extends Mock implements ProcessManager {} class MockProcessManager extends Mock implements ProcessManager {}
class MockProcess extends Mock implements Process {}
class MockPlatform extends Mock implements Platform {} class MockPlatform extends Mock implements Platform {}
class MockHttpServer extends Mock implements HttpServer {} class MockHttpServer extends Mock implements HttpServer {}
......
...@@ -476,7 +476,7 @@ void main() { ...@@ -476,7 +476,7 @@ void main() {
try { try {
await device.takeScreenshot(globals.fs.file('file.ppm')); await device.takeScreenshot(globals.fs.file('file.ppm'));
} catch (_) { } on Exception {
assert(false); assert(false);
} }
expect( expect(
...@@ -534,8 +534,8 @@ void main() { ...@@ -534,8 +534,8 @@ void main() {
try { try {
await device.takeScreenshot(globals.fs.file('file.ppm')); await device.takeScreenshot(globals.fs.file('file.ppm'));
} catch (_) { } on Exception catch (e) {
assert(false); fail('Unexpected exception: $e');
} }
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
ProcessManager: () => mockProcessManager, ProcessManager: () => mockProcessManager,
......
...@@ -229,9 +229,9 @@ void main() { ...@@ -229,9 +229,9 @@ void main() {
Map<String, String> signingConfigs; Map<String, String> signingConfigs;
try { try {
signingConfigs = await getCodeSigningIdentityDevelopmentTeam(iosApp: app); signingConfigs = await getCodeSigningIdentityDevelopmentTeam(iosApp: app);
} catch (e) { } on Exception catch (e) {
// This should not throw // This should not throw
expect(true, false); fail('Code signing threw: $e');
} }
expect(testLogger.statusText, contains('Apple Development: Profile 1 (1111AAAA11)')); expect(testLogger.statusText, contains('Apple Development: Profile 1 (1111AAAA11)'));
......
...@@ -54,7 +54,7 @@ void main() { ...@@ -54,7 +54,7 @@ void main() {
expect(portForwarder.forwardedPorts.length, 2); expect(portForwarder.forwardedPorts.length, 2);
try { try {
await portForwarder.dispose(); await portForwarder.dispose();
} catch (e) { } on Exception catch (e) {
fail('Encountered exception: $e'); fail('Encountered exception: $e');
} }
expect(portForwarder.forwardedPorts.length, 0); expect(portForwarder.forwardedPorts.length, 0);
......
...@@ -355,7 +355,7 @@ void main() { ...@@ -355,7 +355,7 @@ void main() {
engineDir: 'engine/path', engineDir: 'engine/path',
); );
fail('ToolExit expected'); fail('ToolExit expected');
} catch(e) { } on Exception catch (e) {
expect(e, isA<ToolExit>()); expect(e, isA<ToolExit>());
verifyNever(mockProcessManager.run( verifyNever(mockProcessManager.run(
argThat(containsAllInOrder(<String>['pod', 'install'])), argThat(containsAllInOrder(<String>['pod', 'install'])),
...@@ -404,7 +404,7 @@ Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by ...@@ -404,7 +404,7 @@ Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by
engineDir: 'engine/path', engineDir: 'engine/path',
); );
fail('ToolExit expected'); fail('ToolExit expected');
} catch (e) { } on Exception catch (e) {
expect(e, isA<ToolExit>()); expect(e, isA<ToolExit>());
expect( expect(
testLogger.errorText, testLogger.errorText,
......
...@@ -528,7 +528,7 @@ class FlutterRunTestDriver extends FlutterTestDriver { ...@@ -528,7 +528,7 @@ class FlutterRunTestDriver extends FlutterTestDriver {
// have already completed. // have already completed.
_currentRunningAppId = (await started)['params']['appId'] as String; _currentRunningAppId = (await started)['params']['appId'] as String;
prematureExitGuard.complete(); prematureExitGuard.complete();
} catch (error, stackTrace) { } on Exception catch (error, stackTrace) {
prematureExitGuard.completeError(error, stackTrace); prematureExitGuard.completeError(error, stackTrace);
} }
}()); }());
...@@ -732,7 +732,7 @@ class FlutterTestTestDriver extends FlutterTestDriver { ...@@ -732,7 +732,7 @@ class FlutterTestTestDriver extends FlutterTestDriver {
Map<String, dynamic> _parseJsonResponse(String line) { Map<String, dynamic> _parseJsonResponse(String line) {
try { try {
return castStringKeyedMap(json.decode(line)); return castStringKeyedMap(json.decode(line));
} catch (e) { } on Exception {
// Not valid JSON, so likely some other output. // Not valid JSON, so likely some other output.
return null; return null;
} }
...@@ -771,7 +771,7 @@ Map<String, dynamic> parseFlutterResponse(String line) { ...@@ -771,7 +771,7 @@ Map<String, dynamic> parseFlutterResponse(String line) {
try { try {
final Map<String, dynamic> response = castStringKeyedMap(json.decode(line)[0]); final Map<String, dynamic> response = castStringKeyedMap(json.decode(line)[0]);
return response; return response;
} catch (e) { } on Exception {
// Not valid JSON, so likely some other output that was surrounded by [brackets] // Not valid JSON, so likely some other output that was surrounded by [brackets]
return null; return null;
} }
......
...@@ -139,7 +139,8 @@ Future<void> expectToolExitLater(Future<dynamic> future, Matcher messageMatcher) ...@@ -139,7 +139,8 @@ Future<void> expectToolExitLater(Future<dynamic> future, Matcher messageMatcher)
fail('ToolExit expected, but nothing thrown'); fail('ToolExit expected, but nothing thrown');
} on ToolExit catch(e) { } on ToolExit catch(e) {
expect(e.message, messageMatcher); expect(e.message, messageMatcher);
} catch(e, trace) { // Catch all exceptions to give a better test failure message.
} catch (e, trace) { // ignore: avoid_catches_without_on_clauses
fail('ToolExit expected, got $e\n$trace'); fail('ToolExit expected, got $e\n$trace');
} }
} }
......
...@@ -148,7 +148,8 @@ void testUsingContext( ...@@ -148,7 +148,8 @@ void testUsingContext(
return await testMethod(); return await testMethod();
}, },
); );
} catch (error) { // This catch rethrows, so doesn't need to catch only Exception.
} catch (error) { // ignore: avoid_catches_without_on_clauses
_printBufferedErrors(context); _printBufferedErrors(context);
rethrow; rethrow;
} }
......
...@@ -398,7 +398,8 @@ class MemoryIOSink implements IOSink { ...@@ -398,7 +398,8 @@ class MemoryIOSink implements IOSink {
(List<int> data) { (List<int> data) {
try { try {
add(data); add(data);
} catch (err, stack) { // Catches all exceptions to propagate them to the completer.
} catch (err, stack) { // ignore: avoid_catches_without_on_clauses
sub.cancel(); sub.cancel();
completer.completeError(err, stack); completer.completeError(err, stack);
} }
......
...@@ -73,7 +73,8 @@ class VMPlatform extends PlatformPlugin { ...@@ -73,7 +73,8 @@ class VMPlatform extends PlatformPlugin {
Isolate isolate; Isolate isolate;
try { try {
isolate = await _spawnIsolate(codePath, receivePort.sendPort); isolate = await _spawnIsolate(codePath, receivePort.sendPort);
} catch (error) { // This catch rethrows, so doesn't need to catch only Exception.
} catch (error) { // ignore: avoid_catches_without_on_clauses
receivePort.close(); receivePort.close();
rethrow; rethrow;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment