-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
exception.dart
76 lines (66 loc) 路 2.53 KB
/
exception.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// ignore_for_file: require_trailing_commas
// Copyright 2020, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/services.dart';
/// Catches a [PlatformException] and returns an [Exception].
///
/// If the [Exception] is a [PlatformException], a [FirebaseException] is returned.
Never convertPlatformExceptionToFirebaseException(
Object exception,
StackTrace rawStackTrace, {
required String plugin,
}) {
var stackTrace = rawStackTrace;
if (stackTrace == StackTrace.empty) {
stackTrace = StackTrace.current;
}
if (exception is! PlatformException) {
Error.throwWithStackTrace(exception, stackTrace);
}
Error.throwWithStackTrace(
platformExceptionToFirebaseException(exception, plugin: plugin),
stackTrace,
);
}
/// Converts a [PlatformException] into a [FirebaseException].
///
/// A [PlatformException] can only be converted to a [FirebaseException] if the
/// `details` of the exception exist. Firebase returns specific codes and messages
/// which can be converted into user friendly exceptions.
FirebaseException platformExceptionToFirebaseException(
PlatformException platformException, {
required String plugin,
}) {
Map<String, String>? details = platformException.details != null
? Map<String, String>.from(platformException.details)
: null;
String? code;
String message = platformException.message ?? '';
if (details != null) {
code = details['code'] ?? code;
message = details['message'] ?? message;
}
return FirebaseException(
plugin: plugin,
code: code,
message: message,
);
}
/// A custom [EventChannel] with default error handling logic.
extension EventChannelExtension on EventChannel {
/// Similar to [receiveBroadcastStream], but with enforced error handling.
Stream<dynamic> receiveGuardedBroadcastStream({
dynamic arguments,
required dynamic Function(Object error, StackTrace stackTrace) onError,
}) {
final incomingStackTrace = StackTrace.current;
return receiveBroadcastStream(arguments).handleError((Object error) {
// TODO(rrousselGit): use package:stack_trace to merge the error's StackTrace with "incomingStackTrace"
// This TODO assumes that EventChannel is updated to actually pass a StackTrace
// (as it currently only sends StackTrace.empty)
return onError(error, incomingStackTrace);
});
}
}