Flutter错误处理简化插件error_handling_ease的使用

Flutter错误处理简化插件error_handling_ease的使用

概述

error_handling_ease 是一个用于简化 Flutter 错误处理的插件。它通过封装函数和全局配置,自动记录和报告错误,从而减少重复代码,并统一处理异常和错误。


解决方案

问题与解决方案对比表

问题 解决方案
每次捕获错误时重复编写日志和记录代码(如 Crashlytics、Sentry 或 Instabug)。 使用函数包装器和全局配置自动记录和报告错误。
调用可能抛出异常的函数时未使用 try-catch 包裹。 返回类型为 <Either<Failure, T>>fpDart 包,强制我们处理异常。
需要跨应用统一处理第三方包的自定义异常(如 FirebaseAuthExceptionDioException)。 全局配置处理所有自定义异常类型。
手动将所有错误和异常转换为简单的消息(如“抱歉!发生了一些错误。”)。 全局配置可以为所有无自定义消息的错误设置默认 UI 提示。
catch 块中记录的所有异常也包括一些简单的异常(如 UserNotRegistedException)。 可以配置如何处理 EaseExceptionEaseError 这两种类型的失败。
不够友好的解析错误日志(如“参数类型 ‘int’ 无法分配给参数类型 ‘String’”)。 全局可配置的日志格式,例如:“解析用户 ID ‘12345’ 失败,未解析数据:{‘id’: ‘12345’, …}”。
使用多层架构时意外多次记录同一异常。 日志/报告仅在整个异常生命周期内发生一次。
自定义异常消息在高层逻辑中意外丢失。 保留原始异常直到顶层处理。

EaseFailure 类型

EaseFailure 是该库中所有函数返回的对象类型。它有两个子类:EaseExceptionEaseError

EaseFailure 类图


Exceptions vs Errors

异常 (Exceptions)

  • 预期性错误:应该被处理。
  • 示例:如果用户未登录,则抛出 UserNotSignedInException。这种情况是可预见的,因此不会记录到 Crash Reporting 系统中。

错误 (Errors)

  • 非预期性错误:应避免的编程错误。
  • 示例:当数据解析失败时,我们通常只能向用户显示错误消息,但需要记录此错误以便后端修复。
特性 异常 (Exceptions) 错误 (Errors)
是否预期
是否需要处理
是否需要记录到 Crash Reporting

EaseException

EaseExceptionEaseFailure 的子类,用于处理预期性错误。

class UserNotRegisteredException extends EaseException {  
  UserNotRegisteredException() : super('Please enter your details to continue.');  
}
Future<User> fetchUserOfId(String userId) async {
  final userDoc = await FirebaseFirestore.instance.collection('users').doc(userId).get();
  
  if (!userDoc.exists) throw UserNotRegisteredException(); // 抛出 EaseException
  
  return User.fromJson(userDoc.data()!);
}

EaseError

EaseErrorEaseFailure 的子类,用于处理非预期性错误。

class DocNotFoundError<T> extends EaseError {  
  DocNotFoundError(this.docPath)  
      : super(  
          'Failed to fetch ${T.toString()} doc of path $docPath',  
          '${T.toString()} doc not found',  
          StackTrace.current,
          infoParams: {'docPath': docPath},  
        );  

  final String docPath;  
}
Future<School> fetchSchoolOfId(String schoolId) async {
  final doc = FirebaseFirestore.instance.collection('schools').doc(schoolId);
  final schoolDoc = await doc.get();

  if (!schoolDoc.exists) throw DocNotFoundError<School>(doc.path); // 抛出 EaseError
  
  return School.fromJson(schoolDoc.data()!);
}

如何使用

步骤 1 - 全局失败配置

我们需要配置如何处理 EaseErrorEaseException

EaseFailure.configure(
  exceptionActions: (message) => Logger().w(message),
  errorActions: (e, s, log, isFatal, infoParams) {
    Logger().e(log, error: e, stackTrace: s);
    CrashReporter.recordError(e, s, log, infoParams: infoParams, fatal: isFatal);
  },
  defaultErrorMessage: 'Something went wrong. Please try again!',
  parsingErrorLogCallback: (type, unParsedData) =>
      'Failed to parse ${type.toString()} of id ${unParsedData['id']}',
  customErrorParsers: {
    FirebaseAuthException: (e, s) {  
      final errorCodeMessageMap = <String, String>{  
        'invalid-email': 'The email entered is invalid. Please check again!',  
        'wrong-password': 'Email or password is incorrect. Please check again!',  
        'email-already-in-use': 'Email already in use. Please try signing in.',  
      };  
      final message = errorCodeMessageMap[(e as FirebaseAuthException).code];  
      if (message != null) return EaseException(message);  
      
      return EaseError('Firebase Auth Exception - ${e.code}', e, s);  
    },  
  },
);

步骤 2 - 使用 EaseEither 包装函数

同步函数包装 - tryRun()

Either<EaseFailure, double> sumOfList(List list) {  
  return tryRun(() {  
    return list.fold(0, (prev, e) => prev + e);  
  }, 'Failed to find sum of list', infoParams: {'list': list});  
}

异步函数包装 - tryRunAsync()

Future<School> fetchSchoolOfId(String schoolId) async {
  final doc = FirebaseFirestore.instance.collection('schools').doc(schoolId);
  final schoolDoc = await doc.get();

  if (!schoolDoc.exists) throw DocNotFoundError<School>(doc.path); // 抛出 EaseError
  
  return School.fromJson(schoolDoc.data()!);
}

解析包装 - EaseEither.tryParse()

Either<EaseFailure, int> getFirstNumber(List<int> numbers) {
  return tryRun(
    () => numbers[0],
    'Failed to get first number',
    infoParams: {'numbers': numbers},
    uiMessage: 'Something went wrong! Please try with different numbers',
    isFatal: true,
  );
}

步骤 3 - 抛出 EaseErrorEaseException

示例:抛出 EaseException

User getSignedInUser() {
  final currentUser = _getCurrentUser();
  if (currentUser == null) throw EaseException('Please sign in to continue');
  return currentUser;
}

示例:抛出 EaseError

Future<File> downloadFileOfUrl(String url) async {
  final file = await _downloadFile(url);
  if (file == null) throw EaseError('Failed to download file');
  return file;
}

全局配置详解

errorActions

用于处理非预期性错误(EaseError)。

errorActions: (e, s, log, isFatal, infoParams) {
  Logger().e(log, error: e, stackTrace: s);
  CrashReporter.recordError(e, s, log, infoParams: infoParams, fatal: isFatal);
},

exceptionActions

用于处理预期性错误(EaseException)。

exceptionActions: (message) => Logger().w(message),

defaultErrorMessage

默认错误提示信息。

defaultErrorMessage: 'Something went wrong. Please try again!',

customErrorParsers

自定义错误解析逻辑。

customErrorParsers: {
  FirebaseAuthException: (e, s) {  
    final errorCodeMessageMap = <String, String>{  
      'invalid-email': 'The email entered is invalid. Please check again!',  
      'wrong-password': 'Email or password is incorrect. Please check again!',  
      'email-already-in-use': 'Email already in use. Please try signing in.',  
    };  
    final message = errorCodeMessageMap[(e as FirebaseAuthException).code];  
    if (message != null) return EaseException(message);  
      
    return EaseError('Firebase Auth Exception - ${e.code}', e, s);  
  },  
},

示例代码

final firstNumber = getFirstNumber([]);
firstNumber.fold(
  (l) => print('l.uiMessage -> ${l.uiMessage}'), 
  (r) => print('r -> $r'),
);

Either<EaseFailure, int> getFirstNumber(List<int> numbers) {
  return tryRun(
    () => numbers[0], 
    'Failed to get first number', 
    infoParams: {'numbers': numbers},
    uiMessage: 'Something went wrong! Please try with different numbers',
    isFatal: true,
  );
}

运行结果:

e -> RangeError (length): Invalid value: Valid value range is empty: 0
log -> Failed to get first number
infoParams -> {numbers: []}
isFatal -> true
l.uiMessage -> Something went wrong! Please try with different numbers

更多关于Flutter错误处理简化插件error_handling_ease的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter错误处理简化插件error_handling_ease的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


error_handling_ease 是一个用于简化 Flutter 应用中错误处理的插件。它提供了一种便捷的方式来捕获、处理和显示错误,减少样板代码,使错误处理更加简洁和一致。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 error_handling_ease 依赖:

dependencies:
  flutter:
    sdk: flutter
  error_handling_ease: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

基本使用

1. 捕获并处理错误

error_handling_ease 提供了一个 tryCatch 方法来简化错误捕获和处理。你可以在任何需要捕获错误的地方使用它。

import 'package:error_handling_ease/error_handling_ease.dart';

void main() {
  tryCatch(
    tryBlock: () {
      // 可能会抛出异常的代码
      throw Exception('Something went wrong!');
    },
    catchBlock: (error, stackTrace) {
      // 处理错误
      print('Caught error: $error');
    },
    finallyBlock: () {
      // 无论是否发生错误都会执行的代码
      print('Finally block executed.');
    },
  );
}

2. 显示错误信息

error_handling_ease 还提供了一个 showErrorSnackbar 方法,用于在 UI 中显示错误信息。

import 'package:flutter/material.dart';
import 'package:error_handling_ease/error_handling_ease.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Error Handling Ease Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              tryCatch(
                tryBlock: () {
                  throw Exception('Something went wrong!');
                },
                catchBlock: (error, stackTrace) {
                  showErrorSnackbar(context, 'Error: $error');
                },
              );
            },
            child: Text('Throw Error'),
          ),
        ),
      ),
    );
  }
}

高级用法

1. 自定义错误处理

你可以通过继承 ErrorHandler 类来自定义错误处理逻辑。

import 'package:error_handling_ease/error_handling_ease.dart';

class CustomErrorHandler extends ErrorHandler {
  [@override](/user/override)
  void handleError(dynamic error, StackTrace stackTrace) {
    // 自定义错误处理逻辑
    print('Custom error handler: $error');
  }
}

void main() {
  ErrorHandler.setHandler(CustomErrorHandler());

  tryCatch(
    tryBlock: () {
      throw Exception('Custom error handling!');
    },
  );
}

2. 全局错误捕获

你可以在应用程序的入口处设置全局错误捕获,以确保所有未捕获的异常都能被处理。

import 'package:flutter/material.dart';
import 'package:error_handling_ease/error_handling_ease.dart';

void main() {
  ErrorHandler.setGlobalHandler((error, stackTrace) {
    print('Global error handler: $error');
  });

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Global Error Handling Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              throw Exception('Global error!');
            },
            child: Text('Throw Global Error'),
          ),
        ),
      ),
    );
  }
}
回到顶部