올바른 자세를 트래핑 플러터 오류

배경

우리는 소프트웨어 개발 과정에서 오류 및 예외는 항상 피할 것을 알고있다.

클라이언트가 논리적 오류 한 예외가 있었다으로, 발생, 또는 데이터 서버 문제가 발생할이든, 우리 모두가 다루는 정보를 통보하는 메커니즘이 필요합니다.

APP의 개발, 우리는 등 패브릭, Bugly, 같은 일부 타사 플랫폼, 특별한 로그 보고서를 얻을 수 있습니다 통과시켰다.

떨림은 비정상적인 로그 보고서를 달성 할 수있는 등의 센트리와 같은 일부 타사 플랫폼이 있습니다.

그러나 일반적인 본의 일부,이 타사 플랫폼은, 우리가 어떻게 내부 떨림에 예외를 포착하는 방법을 알려드립니다 예외 로그 캡처 자세히 설명하지 않습니다.

특정 에스컬레이션 경로에 관해서는, 제삼자에 의해보고되는 자신의 서버 또는 비정상적인 SDK의 API 인터페이스에 다시보고 여부, 그것은 가능하다.

데모 초기 상태

다음과 같이 첫째, 수정, 새로운 떨림 프로젝트를 생성 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을 수정 한 다음, 목록에게 국경 액세스를 추가 다음과 같이 몇 가지 코드가 변경 :

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

물론, 이러한 오류 메시지는 또한 인터페이스 (디버그 모드)에 표시됩니다.

어떻게 우리는 그것을 캡처합니까?

사실 매우 간단하고 일반적인 템플릿이 템플릿은 다음과 같습니다

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

마법을 주장

우리는 일반적으로 오류보고에 포장되고, 필요 후 시장에 출시 된 것을 알고있다.

일반적으로 오류가 발생하는 경우, 우리가 찾아 문제를 해결합니다 디버깅 할 때.

따라서, 디버그 모드에서, 우리는 오류를보고 싶지 않아,하지만 당신은 콘솔에 직접 인쇄 할 수 있습니다.

글쎄, 우리가 지금해야 할이 시간이 디버그 모드와 릴리스 모드를 구별 할 수있는 방법이며, 어떻게 구별 하는가?

이 시간 우리는 어설 사용해야합니다.

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

코멘트도 알 수에서 만 개발 환경에서 작동 식을 주장, 제품 환경에서 무시됩니다.

그래서 우리는 우리의 요구를 달성 할 수있다,이 활용합니다.

위의 결론을 확인하려면 매우 간단합니다, 우리는 보여주지 않습니다.

전체 템플릿

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

디버그 모드, 직접 인쇄 문제를 쉽게 찾을 수 콘솔에 오류.

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

参考链接:
Report errors to a service

추천

출처www.cnblogs.com/nesger/p/11669489.html