dreampad/lib/app/shared/utils/handle_error_utils.dart
2023-11-28 10:45:09 +08:00

37 lines
1.1 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'package:flutter/widgets.dart';
import '../constants/constants.dart';
/// 捕获全局异常,进行统一处理。
void handleError(void Function() body) {
/// 重写Flutter异常回调 FlutterError.onError
FlutterError.onError = (FlutterErrorDetails details) {
if (!Constant.inProduction) {
// debug时直接将异常信息打印。
FlutterError.dumpErrorToConsole(details);
} else {
// release时将异常交由zone统一处理。
Zone.current.handleUncaughtError(details.exception, details.stack!);
}
};
/// 使用runZonedGuarded捕获Flutter未捕获的异常
runZonedGuarded(body, (Object error, StackTrace stackTrace) async {
await _reportError(error, stackTrace);
});
}
Future<void> _reportError(Object error, StackTrace stackTrace) async {
if (!Constant.inProduction) {
debugPrintStack(
stackTrace: stackTrace,
label: error.toString(),
maxFrames: 100,
);
} else {
/// 将异常信息收集并上传到服务器。可以直接使用类似`flutter_bugly`插件处理异常上报。
}
}