Flutter 错误处理与日志
崩溃和无声 bug 是用户体验的杀手。Flutter / Dart 给了完整的错误捕获机制,但默认配置很弱——手动配置才能真正保护线上。
一、Dart 异常基础
try {
doSomething();
} on FormatException catch (e) {
// 特定类型
print(e.message);
} on Exception catch (e, st) {
// 任何 Exception
print('$e\n$st');
} catch (e, st) {
// 任何 throw 的东西(包括非 Exception)
} finally {
cleanup();
}注意点:
on Type catch (e)只捕获该类型catch (e)捕获一切catch (e, st)第二个是 StackTrace- Dart 不强制 checked exception,函数签名不要求声明可能抛什么
Exception vs Error
| 类型 | 用途 |
|---|---|
Exception(及子类) | 业务可恢复异常(网络错、参数错) |
Error(及子类) | 程序员错误(StateError、ArgumentError、TypeError) |
理论上 Error 不该 catch,应该让它崩 + 修代码。Exception 才是用来 catch 处理的。 但实战中往往一起 catch。
二、自定义业务异常
sealed class AppException implements Exception {
final String message;
const AppException(this.message);
@override
String toString() => 'AppException: $message';
}
class NetworkException extends AppException {
const NetworkException(super.message);
}
class UnauthorizedException extends AppException {
const UnauthorizedException() : super('未登录或登录过期');
}
class ServerException extends AppException {
final int statusCode;
const ServerException(super.message, this.statusCode);
}回顾 28 sealed:用 sealed 让 switch 强制穷举所有错误类型。
Dio 转业务异常
AppException _toAppException(DioException e) {
switch (e.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.receiveTimeout:
return const NetworkException('网络超时');
case DioExceptionType.badResponse:
final code = e.response?.statusCode ?? 0;
if (code == 401) return const UnauthorizedException();
return ServerException('服务器错误', code);
default:
return const NetworkException('未知错误');
}
}UI 层只需要处理 AppException,不知道下面是 Dio 还是 GraphQL。
三、async / await 的错误传播
Future<User> fetch() async {
final r = await dio.get('/me'); // 抛 DioException
return User.fromJson(r.data);
}
// 调用方
try {
final u = await fetch();
} on DioException catch (e) {
// ✅ 异步异常会传播到这里
}async 函数内部的异常自动包成 Future.error,await 会重新抛出。
多个 Future 并发的错误
final results = await Future.wait([f1, f2, f3]); // 任一失败,整体抛错
// 想让其他完成
await Future.wait([f1, f2, f3], eagerError: false);回顾 29。
四、Future.then().catchError()
fetch()
.then((u) => print(u))
.catchError((e, st) {
print('错 $e');
})
.whenComplete(() => print('结束'));新代码 99% 用 try/catch + await,只有"火忘"场景用 then/catchError。
容易忽略的:catchError 的 test 参数
fetch()
.catchError((e) => User.guest(), test: (e) => e is NetworkException);只在 NetworkException 时返回 guest,其他错继续传播。
五、Flutter 全局错误捕获
Flutter 把错误分两类:
void main() {
// 1. Flutter 框架内部抛错(build / paint / 手势 / ...)
FlutterError.onError = (details) {
FlutterError.presentError(details); // 默认行为(打印到 console)
// 上报
Sentry.captureException(details.exception, stackTrace: details.stack);
};
// 2. Flutter 框架外的异步错误(isolate、Future、Stream 未捕获)
PlatformDispatcher.instance.onError = (error, stack) {
Sentry.captureException(error, stackTrace: stack);
return true; // 表示已处理
};
runApp(const MyApp());
}老写法:runZonedGuarded(回退方案)
runZonedGuarded(() {
runApp(const MyApp());
}, (error, stack) {
Sentry.captureException(error, stackTrace: stack);
});Flutter 3.3+ 之后,
PlatformDispatcher.onError是更新的方式,推荐用它。runZonedGuarded仍可用作 backup。
六、ErrorWidget:替换"红色错误页"
debug 模式 build 错误显示红条,release 是灰白屏。自定义友好提示:
ErrorWidget.builder = (FlutterErrorDetails details) {
if (kDebugMode) return ErrorWidget(details.exception); // 调试时保留红条
return Material(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.error, size: 48, color: Colors.red),
SizedBox(height: 16),
Text('出错了,请稍后再试'),
],
),
),
);
};放 main 里。
七、try-catch 用在哪一层
业务层(Repository / UseCase)
把底层异常转成业务异常,UI 层处理统一类型:
class UserRepo {
Future<User> getMe() async {
try {
return await api.getMe();
} on DioException catch (e) {
throw _toAppException(e);
}
}
}UI 层(Cubit / 事件回调)
Future<void> login(String email, String pwd) async {
emit(AuthLoading());
try {
final user = await repo.login(email, pwd);
emit(AuthSuccess(user));
} on UnauthorizedException {
emit(AuthError('账号或密码错'));
} on AppException catch (e) {
emit(AuthError(e.message));
} catch (e, st) {
Sentry.captureException(e, stackTrace: st);
emit(AuthError('未知错误'));
}
}不要在 build 里 try-catch
@override
Widget build(BuildContext context) {
try {
return SomeWidget(...); // ⚠️ build 里不要业务 try
} catch (e) {
return ErrorWidget(e);
}
}build 应该是纯函数。错误处理放在 build 之前(Cubit / Provider)。
八、Result / Either:错误显式化
抛异常容易"遗忘",Result 让"成功 / 失败"进入类型系统:
sealed class Result<T> {
const Result();
}
class Ok<T> extends Result<T> {
final T value;
const Ok(this.value);
}
class Err<T> extends Result<T> {
final AppException error;
const Err(this.error);
}
// Repository
Future<Result<User>> getMe() async {
try {
return Ok(await api.getMe());
} on DioException catch (e) {
return Err(_toAppException(e));
}
}
// 调用
final r = await repo.getMe();
switch (r) {
case Ok(:final value):
emit(AuthSuccess(value));
case Err(:final error):
emit(AuthError(error.message));
}社区库:fpdart(Either / Option)、dartz、oxidized。
好处:编译器强制处理失败。 缺点:写起来啰嗦,初学者难。
实战团队选哪个看偏好,没必要全项目都 Result,关键路径用就行。
九、日志:print / debugPrint / logger
print 不要用于生产
print('hi'); // ⚠️ 在 release 包里也会输出,泄露信息debugPrint:release 里被裁掉
debugPrint('hi'); // 只在 debug 输出但 debugPrint 也有限流(防止 logcat 截断),大文本可能丢。
推荐:logger 包
dependencies:
logger: ^2.4.0final logger = Logger(
printer: PrettyPrinter(
methodCount: 2,
errorMethodCount: 8,
lineLength: 120,
colors: true,
printEmojis: true,
),
);
logger.d('debug 信息');
logger.i('info');
logger.w('warning');
logger.e('error', error: err, stackTrace: st);
logger.f('fatal');带颜色、emoji、调用栈,看着舒服得多。
生产环境过滤
final logger = Logger(
level: kDebugMode ? Level.trace : Level.warning,
// release 只输出 warning 以上
);十、崩溃监控:Sentry
回顾 19:
dependencies:
sentry_flutter: ^8.9.0await SentryFlutter.init(
(options) {
options.dsn = 'https://...';
options.tracesSampleRate = 0.1; // 10% 采样性能数据
options.environment = kReleaseMode ? 'production' : 'development';
options.release = 'myapp@1.2.3+45';
},
appRunner: () => runApp(const MyApp()),
);会自动接管 FlutterError.onError 和 PlatformDispatcher.instance.onError。
手动上报
try {
await risky();
} catch (e, st) {
await Sentry.captureException(e, stackTrace: st);
}加上下文
Sentry.configureScope((scope) async {
scope.setUser(SentryUser(id: user.id, email: user.email));
scope.setTag('feature', 'checkout');
scope.setExtra('cart_size', items.length);
});崩溃报上来时带这些上下文,排查极快。
面包屑(Breadcrumbs)
Sentry.addBreadcrumb(Breadcrumb(
message: '用户点了下单',
category: 'ui.click',
));崩溃前的最后几个动作就被记录。
替代:Firebase Crashlytics
更轻、免费,但功能比 Sentry 简单。回顾 19。
十一、把崩溃日志映射回源码
release 包代码混淆后,堆栈是这样:
#0 _$_xx (build/symbols/abc.dart:17:5)需要 debug-info 文件 才能解析:
flutter build apk --release --obfuscate --split-debug-info=build/symbols把 build/symbols/ 上传到 Sentry / Crashlytics。崩溃显示时自动反混淆。
回顾 19。
十二、网络请求专项:Dio 错误拦截
dio.interceptors.add(InterceptorsWrapper(
onError: (err, handler) async {
// 401 → 刷 token + 重试
if (err.response?.statusCode == 401) {
try {
await _refreshToken();
final clone = await dio.fetch(err.requestOptions);
return handler.resolve(clone);
} catch (_) {
// 刷失败,登出
}
}
// 上报
if (err.response?.statusCode != null && err.response!.statusCode! >= 500) {
Sentry.captureException(err);
}
handler.next(err);
},
));回顾 13。
十三、UI 错误反馈
让用户看到友好提示:
BlocListener<AuthCubit, AuthState>(
listener: (context, state) {
if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.message)),
);
}
},
child: ...,
)或全局 listener:
ref.listen(errorProvider, (_, error) {
if (error != null) showErrorDialog(context, error);
});十四、调试工具
debugger() 暂停
import 'dart:developer';
if (somethingBad) debugger(); // IDE 在这里暂停,可以单步dart:developer log
import 'dart:developer' as dev;
dev.log('hi', name: 'feature.auth');DevTools 的 Logging 标签会分类显示。
inspect
import 'dart:developer';
inspect(complexObject);DevTools 里弹出对象详情。
十五、单元测试 expect 异常
test('age < 0 抛错', () {
expect(() => User(age: -1), throwsArgumentError);
expect(() => doIt(), throwsA(isA<NetworkException>()));
});
test('Future 异常', () async {
expect(fetch(), throwsA(isA<TimeoutException>()));
});回顾 20。
十六、常见反模式
1. 吃异常
try {
await save();
} catch (_) {} // ❌ 完全吞,出错没人知道→ 至少打日志或上报。
2. 在 catch 里 throw e
} catch (e) {
throw e; // ⚠️ 丢了 stacktrace
}
// ✅
} catch (e, st) {
throw Error.throwWithStackTrace(e, st);
}
// 或更简单:
} catch (_) {
rethrow;
}3. 用 String 当异常
throw '失败'; // ⚠️ 合法但烂,catch 时没法区分→ 自定义异常类,或至少 Exception('失败')。
4. 把 Error 当 Exception 处理
try {
myList[100];
} catch (_) { /* 忽略 RangeError */ }→ Error 是程序员错误,应该改代码不该 catch。
5. UI 层硬编码错误文案
catch (e) {
showSnackBar('网络错误,请检查'); // ❌ 国际化呢?
}→ 用 l10n + 错误码(回顾 17)。
十七、错误处理体系建议
1. 业务异常分类(NetworkException / UnauthorizedException / ...)
2. Repository 把底层异常转业务异常
3. UI 层(Cubit)按异常类型 emit 不同状态
4. UI 用 Listener / BlocListener 显示反馈
5. main 里全局兜底:FlutterError.onError + PlatformDispatcher.onError
6. 崩溃上报 Sentry / Crashlytics
7. 关键路径加面包屑
8. 生产环境 logger 只 warning+
9. release 加 --obfuscate + --split-debug-info,符号上传十八、一个完整 main 模板
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// 全局 ErrorWidget
ErrorWidget.builder = (details) {
if (kDebugMode) return ErrorWidget(details.exception);
return const _FriendlyErrorWidget();
};
// Sentry 自动接管 FlutterError + PlatformDispatcher
await SentryFlutter.init(
(options) {
options.dsn = const String.fromEnvironment('SENTRY_DSN');
options.environment = kReleaseMode ? 'production' : 'development';
options.release = '${packageInfo.version}+${packageInfo.buildNumber}';
options.tracesSampleRate = 0.1;
},
appRunner: () => runApp(const MyApp()),
);
}十九、和已学知识的串联
- async/await 错误传播(29)
- Repository 抽象 + 异常转换(21)
- Bloc / Riverpod 用 sealed 状态包错误(10 / 09)
- Dio 拦截器统一处理(13)
- 上线打混淆 symbol 上传(19)
- Sentry / Crashlytics 集成(19)
- 国际化错误文案(17)
- 测试 throwsA(20)
二十、心智模型
错误三层防线:
1. 业务层(可预期)
- try-catch 转业务异常
- 用类型表达"成功/失败"(Result / sealed)
2. UI 层(展示)
- listener 监听异常状态 → SnackBar / Dialog
- ErrorWidget.builder 兜底
3. 全局(兜底)
- FlutterError.onError → Sentry
- PlatformDispatcher.onError → Sentry
- Zone(老方案)线上 App 没有崩溃监控就是裸奔。配置 Sentry / Crashlytics 半小时,挽回的用户和反馈无价。
错误处理不是写多就好,关键是有体系:每种业务异常对应明确的 UI 反馈,所有未捕获的统一上报。这样用户和你都不会"无声失败"。