crash_reporting.dart 4.58 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
9
import 'package:stack_trace/stack_trace.dart';
10 11

import 'base/io.dart';
12 13
import 'base/os.dart';
import 'base/platform.dart';
14 15 16 17
import 'globals.dart';
import 'usage.dart';

/// Tells crash backend that the error is from the Flutter CLI.
18
const String _kProductId = 'Flutter_Tools';
19 20

/// Tells crash backend that this is a Dart error as opposed to, say, Java.
21
const String _kDartTypeId = 'DartError';
22 23

/// Crash backend host.
24
const String _kCrashServerHost = 'clients2.google.com';
25 26

/// Path to the crash servlet.
27
const String _kCrashEndpointPath = '/cr/report';
28 29 30

/// The field corresponding to the multipart/form-data file attachment where
/// crash backend expects to find the Dart stack trace.
31
const String _kStackTraceFileField = 'DartError';
32 33 34 35 36

/// The name of the file attached as [_kStackTraceFileField].
///
/// The precise value is not important. It is ignored by the crash back end, but
/// it must be supplied in the request.
37
const String _kStackTraceFilename = 'stacktrace_file';
38 39

/// Sends crash reports to Google.
40
///
41
/// There are two ways to override the behavior of this class:
42
///
43 44 45 46 47 48 49
/// * Define a `FLUTTER_CRASH_SERVER_BASE_URL` environment variable that points
///   to a custom crash reporting server. This is useful if your development
///   environment is behind a firewall and unable to send crash reports to
///   Google, or when you wish to use your own server for collecting crash
///   reports from Flutter Tools.
/// * In tests call [initializeWith] and provide a mock implementation of
///   [http.Client].
50 51 52
class CrashReportSender {
  CrashReportSender._(this._client);

53 54
  static CrashReportSender _instance;

55
  static CrashReportSender get instance => _instance ?? CrashReportSender._(http.Client());
56 57 58 59

  /// Overrides the default [http.Client] with [client] for testing purposes.
  @visibleForTesting
  static void initializeWith(http.Client client) {
60
    _instance = CrashReportSender._(client);
61 62 63 64 65
  }

  final http.Client _client;
  final Usage _usage = Usage.instance;

66 67 68 69 70 71
  Uri get _baseUrl {
    final String overrideUrl = platform.environment['FLUTTER_CRASH_SERVER_BASE_URL'];

    if (overrideUrl != null) {
      return Uri.parse(overrideUrl);
    }
72
    return Uri(
73 74 75 76 77 78 79
      scheme: 'https',
      host: _kCrashServerHost,
      port: 443,
      path: _kCrashEndpointPath,
    );
  }

80 81 82
  /// Sends one crash report.
  ///
  /// The report is populated from data in [error] and [stackTrace].
83
  Future<void> sendReport({
84
    @required dynamic error,
85
    @required StackTrace stackTrace,
86
    @required String getFlutterVersion(),
87 88 89
  }) async {
    try {
      if (_usage.suppressAnalytics)
90
        return;
91 92 93

      printStatus('Sending crash report to Google.');

94
      final String flutterVersion = getFlutterVersion();
95
      final Uri uri = _baseUrl.replace(
96 97 98 99 100 101
        queryParameters: <String, String>{
          'product': _kProductId,
          'version': flutterVersion,
        },
      );

102
      final http.MultipartRequest req = http.MultipartRequest('POST', uri);
103
      req.fields['uuid'] = _usage.clientId;
104 105
      req.fields['product'] = _kProductId;
      req.fields['version'] = flutterVersion;
106
      req.fields['osName'] = platform.operatingSystem;
107
      req.fields['osVersion'] = os.name; // this actually includes version
108 109
      req.fields['type'] = _kDartTypeId;
      req.fields['error_runtime_type'] = '${error.runtimeType}';
110
      req.fields['error_message'] = '$error';
111

112 113
      final String stackTraceWithRelativePaths = Chain.parse(stackTrace.toString()).terse.toString();
      req.files.add(http.MultipartFile.fromString(
114
        _kStackTraceFileField,
115
        stackTraceWithRelativePaths,
116 117 118
        filename: _kStackTraceFilename,
      ));

119
      final http.StreamedResponse resp = await _client.send(req);
120 121

      if (resp.statusCode == 200) {
122
        final String reportId = await http.ByteStream(resp.stream)
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
            .bytesToString();
        printStatus('Crash report sent (report ID: $reportId)');
      } else {
        printError('Failed to send crash report. Server responded with HTTP status code ${resp.statusCode}');
      }
    } catch (sendError, sendStackTrace) {
      if (sendError is SocketException) {
        printError('Failed to send crash report due to a network error: $sendError');
      } else {
        // If the sender itself crashes, just print. We did our best.
        printError('Crash report sender itself crashed: $sendError\n$sendStackTrace');
      }
    }
  }
}