Flutter 新聞客戶端 - 12 採用 sentry 平臺收集錯誤

會煮咖啡的貓發表於2020-06-24

Flutter 新聞客戶端 - 12 採用 sentry 平臺收集錯誤

B站視訊

www.bilibili.com/video/BV1Ek…

本節目標

  • 使用 sentry 平臺
  • flutter 整合
  • android 整合
  • ios 整合

正文

錯誤收集策略

Flutter 新聞客戶端 - 12 採用 sentry 平臺收集錯誤

sentry 平臺

sentry.io

收集 flutter

  • 參考

docs.sentry.io/platforms/f…

  • pubspec.yaml
dependencies:
  sentry: ^3.0.1
複製程式碼
  • lib/main.dart
// 建立 SentryClient 用於將異常日誌上報給 sentry 平臺
final SentryClient _sentry = new SentryClient(
  dsn:
      'https://xxxxxxxxxx',
);

// 是否開發環境
bool get isInDebugMode {
  return false; // false 開始上傳 sentry
}

// 上報異常的函式
Future<void> _reportError(dynamic error, dynamic stackTrace) async {
  print('Caught error: $error');
  if (isInDebugMode) {
    print(stackTrace);
  } else {
    final SentryResponse response = await _sentry.captureException(
      exception: error,
      stackTrace: stackTrace,
    );

    if (response.isSuccessful) {
      print('Success! Event ID: ${response.eventId}');
    } else {
      print('Failed to report to Sentry.io: ${response.error}');
    }
  }
}

Future<Null> main() async {
  // 捕獲並上報 Flutter 異常
  FlutterError.onError = (FlutterErrorDetails details) async {
    if (isInDebugMode == true) {
      FlutterError.dumpErrorToConsole(details);
    } else {
      Zone.current.handleUncaughtError(details.exception, details.stack);
    }
  };

  // 捕獲並上報 Dart 異常
  runZonedGuarded(() async {
    await Global.init();
    runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider<AppState>.value(
            value: Global.appState,
          ),
        ],
        child: Consumer<AppState>(builder: (context, appState, _) {
          if (appState.isGrayFilter) {
            return ColorFiltered(
              colorFilter: ColorFilter.mode(Colors.white, BlendMode.color),
              child: NewsApp(),
            );
          } else {
            return NewsApp();
          }
        }),
      ),
    );
  }, (Object error, StackTrace stack) {
    _reportError(error, stack);
  });
}
複製程式碼

收集 android

  • 參考

docs.sentry.io/platforms/a…

  • 整合 sdk
// ADD JCENTER REPOSITORY
repositories {
    jcenter()
}

// ADD COMPATIBILITY OPTIONS TO BE COMPATIBLE WITH JAVA 1.8
android {
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}

// ADD SENTRY ANDROID AS A DEPENDENCY
dependencies {
    // https://github.com/getsentry/sentry-android/releases
    implementation 'io.sentry:sentry-android:{version}'
}
複製程式碼
  • android/app/src/main/AndroidManifest.xml
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="貓哥新聞"
        android:icon="@mipmap/launcher_icon">

        ...

        <!-- sentry -->
        <meta-data android:name="io.sentry.dsn" android:value="xxxxxxxxxxxxxxxxx" />
    </application>
複製程式碼
  • android/app/src/main/kotlin/com/example/flutterducafecatnews/CrashHandler.java
public class CrashHandler implements UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Sentry.captureException(e);
    }
}
複製程式碼
  • android/app/src/main/kotlin/com/example/flutterducafecatnews/MainActivity.kt
import io.sentry.core.Sentry

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        val crashHandler = CrashHandler()
        Thread.setDefaultUncaughtExceptionHandler(crashHandler)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}
複製程式碼

收集 ios

  • 資料

docs.sentry.io/platforms/c…

  • 整合 CocoaPods
platform :ios, '8.0'
use_frameworks! # This is important

target 'YourApp' do
    pod 'Sentry', :git => 'https://github.com/getsentry/sentry-cocoa.git', :tag => '5.1.2'
end
複製程式碼
  • ios/Runner/AppDelegate.swift
{

    SentrySDK.start(options: [
        "dsn": "https://xxxxxxxxxxxxxxxxxxx",
        "debug": true, // Enabled debug when first installing is always helpful
        "enableAutoSessionTracking": true
    ])

    NSSetUncaughtExceptionHandler { exception in
     print(exception)
     SentrySDK.capture(message: exception.description)
     SentrySDK.capture(exception: exception)
    }

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)

  }
複製程式碼

資源

參考

設計稿藍湖預覽

lanhuapp.com/url/lYuz1 密碼: gSKl

藍湖現在收費了,所以檢視標記還請自己上傳 xd 設計稿 商業設計稿檔案不好直接分享, 可以加微信聯絡 ducafecat

程式碼

github.com/ducafecat/f…

相關文章