Flutter 錯誤捕獲的正確姿勢


背景

我們知道,在軟件開發過程中,錯誤和異常總是在所難免。

不管是客戶端的邏輯錯誤導致的,還是服務器的數據問題導致的,只要出現了異常,我們都需要一個機制來通知我們去處理。

在 APP 的開發過程中,我們通過一些第三方的平台,比如 Fabric、Bugly 等可以實現異常的日志上報。

Flutter 也有一些第三方的平台,比如 Sentry 可以實現異常的日志上報。

但是為了更加通用一些,本篇不具體講解配合某個第三方平台的異常日志捕獲,我們會告知大家如何在 Flutter 里面捕獲異常。

至於具體的上報途徑,不管是上報到自家的后台服務器,還是通過第三方的 SDK API 接口進行異常上報,都是可以的。

Demo 初始狀態

首先我們新建 Flutter 項目,修改 main.dart 代碼如下:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Crash Capture'),),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

效果如下:

捕獲錯誤

我們修改 MyHomePage,添加一個 List 然后進行越界訪問,改動部分代碼如下:

class MyHomePage extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   List<String> numList = ['1', '2'];
   print(numList[6]);
   return Container();
 }
}

可以看到控制台報錯如下:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following RangeError was thrown building MyHomePage(dirty):
flutter: RangeError (index): Invalid value: Not in range 0..1, inclusive: 6

當然這些錯誤信息在界面上也有顯示(debug 模式)。

那么我們如何捕獲呢?

其實很簡單,有個通用模板,模板為:

import 'dart:async';

import 'package:flutter/material.dart';

Future<Null> main() async {
  FlutterError.onError = (FlutterErrorDetails details) async {
    Zone.current.handleUncaughtError(details.exception, details.stack);
  };

  runZoned<Future<void>>(() async {
    runApp(MyApp());
  },  onError: (error, stackTrace) async {
    await _reportError(error, stackTrace);
  });
}

Future<Null> _reportError(dynamic error, dynamic stackTrace) async {
  // TODO
}

TODO 里面就可以執行埋點上報操作或者其他處理了。

完整例子如下:

import 'dart:async';

import 'package:flutter/material.dart';

Future<Null> main() async {
  FlutterError.onError = (FlutterErrorDetails details) async {
    Zone.current.handleUncaughtError(details.exception, details.stack);
  };

  runZoned<Future<void>>(() async {
    runApp(MyApp());
  },  onError: (error, stackTrace) async {
    await _reportError(error, stackTrace);
  });
}

Future<Null> _reportError(dynamic error, dynamic stackTrace) async {
  print('catch error='+error);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Crash Capture'),),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<String> numList = ['1', '2'];
    print(numList[6]);
    return Container();
  }
}

運行可以看到控制台捕獲到錯誤如下:

flutter: catch error=RangeError (index): Invalid value: Not in range 0..1, inclusive: 6

assert 妙用

我們知道,一般錯誤上報都是在打包發布到市場后才需要。

平時調試的時候如果遇到錯誤,我們是會定位問題並修復的。

因此在 debug 模式下,我們不希望上報錯誤,而是希望直接打印到控制台。

那么,這個時候就需要一種方式來區分現在是 debug 模式還是 release 模式,怎么區分呢?

這個時候就需要用到 assert 了。

bool get isInDebugMode {
  // Assume you're in production mode.
  bool inDebugMode = false;

  // Assert expressions are only evaluated during development. They are ignored
  // in production. Therefore, this code only sets `inDebugMode` to true
  // in a development environment.
  assert(inDebugMode = true);

  return inDebugMode;
}

從注釋也可以知道,assert 表達式只在開發環境下會起作用,在生產環境下會被忽略。

因此利用這一個,我們就可以實現我們的需求。

上面的結論要驗證也很簡單,我們就不演示了。

完整模板

import 'dart:async';

import 'package:flutter/material.dart';

Future<Null> main() async {
  FlutterError.onError = (FlutterErrorDetails details) async {
    if (isInDebugMode) {
      FlutterError.dumpErrorToConsole(details);
    } else {
      Zone.current.handleUncaughtError(details.exception, details.stack);
    }
  };

  runZoned<Future<void>>(() async {
    runApp(MyApp());
  },  onError: (error, stackTrace) async {
    await _reportError(error, stackTrace);
  });
}

Future<Null> _reportError(dynamic error, dynamic stackTrace) async {
  // TODO
}

bool get isInDebugMode {
  // Assume you're in production mode.
  bool inDebugMode = false;

  // Assert expressions are only evaluated during development. They are ignored
  // in production. Therefore, this code only sets `inDebugMode` to true
  // in a development environment.
  assert(inDebugMode = true);

  return inDebugMode;
}

debug 模式下,直接將錯誤打印到控制台,方便定位問題。

release 模式下,將錯誤信息收集起來,上傳到服務器。

參考鏈接:
Report errors to a service


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM