Flutter error trapping correct posture

background

We know that in the software development process, errors and exceptions are always inevitable.

Whether the client is a logical error caused by, or result in data server issues, as long as there has been an exception, we all need a mechanism to inform us to deal with.

In the development of APP, we passed some third-party platforms, such as Fabric, Bugly, etc. can be achieved unusual log report.

Flutter There are also some third-party platforms, such as Sentry can achieve abnormal log report.

But to some of the more common herein, this does not explain in detail with the exception log capture a third-party platform, we will tell you how to catch exceptions in Flutter inside.

As for the specific escalation path, whether it is to report back to their own server, or abnormal SDK API interface to be reported by third parties, it is possible.

Demo initial state

First, we create a new Flutter project, modify main.dart code is as follows:

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();
  }
}

Results are as follows:

Capture error

We modify MyHomePage, and then add a List cross-border access, alter some code is as follows:

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

You can see the console being given as follows:

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

Of course, these error messages are also displayed on the interface (debug mode).

So how do we capture it?

Actually very simple, there is a general template, the template is:

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
}

In TODO which can be performed Buried or other processing of the report operation.

Complete examples are as follows:

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();
  }
}

You can see the console to run the capture error as follows:

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

assert Magical

We know that, in general error reporting are packaged and released to the market after the needs.

Usually when debugging if errors are encountered, we will locate and fix the problem.

Therefore, in debug mode, we do not want to report the error, but you want to print directly to the console.

Well, this time we need now is a way to distinguish between debug mode or release mode, how to distinguish it?

This time we need to use the 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;
}

From the comments may also know, assert expression will work only in the development environment, it will be ignored in a production environment.

So take advantage of this one, we can achieve our needs.

To verify the above conclusion is very simple, we do not demonstrate.

Complete template

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 mode, direct print an error to the console, easy to locate the problem.

release 模式下,将错误信息收集起来,上传到服务器。

参考链接:
Report errors to a service

Guess you like

Origin www.cnblogs.com/nesger/p/11669489.html