Flutter: How to implement FlutterError.OnError correctly

≯℡__Kan透↙ 提交于 2021-02-07 12:22:27

问题


Can someone show me how to implement overriding flutter errors during widget test so I can check for my own custom errors.

I have seen snippets online mentioning this but all of my implementations fail

void main() {

  testWidgets('throws an error when scanning unknown term types', (WidgetTester tester) async {
    await tester.pumpWidget(injectTestWidget(new ItemScanScreen()));

    await tester.enterText(find.byKey(new Key('term')), '');
    await tester.tap(find.byIcon(Icons.send));
    await tester.pump();

    expect(
      tester.takeException(),
      isInstanceOf<UnrecognizedTermException>(),
      reason: 'should have thrown an UnrecognizedTermException error but didn\'t',
    );
  });
}

the code above fails with the message below even though it looks like it in fact 'caught' my error:

The following UnrecognizedTermException was thrown running a test:
Instance of 'UnrecognizedTermException'
...

I read that you could do something like the snippet below but it did not see how/where to implement it:

final errorHandled = expectAsync0((){});

FlutterError.onError = (errorDetails) {
  // handle error
  errorHandled();
});

回答1:


I use the code below in production to log errors to a server.

main.dart:

import 'dart:async';
import 'package:flutter/material.dart';
import 'logging.dart';

void main() async {
  FlutterError.onError = (FlutterErrorDetails details) async {
    new ErrorLogger().logError(details);
  };
  runZoned<Future<void>>(() async {
    // Your App Here
    runApp(MainApp());
  }, onError: (error, stackTrace) {
    new ErrorLogger().log(error, stackTrace);
  });
}

logging.dart:

class ErrorLogger {

  void logError(FlutterErrorDetails details) async {
    //FlutterError.dumpErrorToConsole(details);
    _sendToServer(details.exceptionAsString(), details.stack.toString());
  }

  void log(Object data, StackTrace stackTrace) async {  
      // print(data);
      // print(stackTrace);
    _sendToServer(data.toString(), stackTrace.toString());
  }

  void _sendToServer(String a, String b) async {
    // Implementation here
  }
}



回答2:


This is was design for a test. I switched to wrapping logic in try/catch then running expect() on the "error message text" present concept. ex:

try {
   throw new UnrecognizedTermException();
 } catch (e) {
   setState(() => _status = e.errMsg());
}

// then in my test
expect(find.text('Could not determine the type of item you scanned'), findsOneWidget);


来源:https://stackoverflow.com/questions/54294656/flutter-how-to-implement-fluttererror-onerror-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!