1 | | | import 'dart:async'; |
2 | | | import 'dart:convert'; |
3 | | |
|
4 | | | import 'package:cancelation_token/cancelation_token.dart'; |
5 | | |
|
6 | | | import '_well_known_exceptions.dart'; |
7 | | | import 'worker_exception.dart'; |
8 | | |
|
9 | | | /// Base abstract class for exceptions in Squadron. |
10 | | | abstract class SquadronException implements Exception { |
11 | | 20 | SquadronException.init(this.message, [this._stackTrace]) { |
12 | | 20 | if (_stackTrace == null) { |
13 | | | try { |
14 | | 26 | _stackTrace = StackTrace.current; |
15 | | 0 | } catch (_, st) { |
16 | | | // failed, take the opportunity to get the stack trace from this exception! |
17 | | 0 | _stackTrace = st; |
18 | | | } |
19 | | | } |
20 | | 10 | } |
21 | | |
|
22 | | | /// This method returns [error] if it is a [SquadronException] (enriching it |
23 | | | /// with [command] if it is a [WorkerException]). Otherwise, it returns a new |
24 | | | /// [WorkerException] wrapping [error] and [stackTrace]. |
25 | | 16 | static SquadronException from(Object error, |
26 | | | [StackTrace? stackTrace, int? command]) { |
27 | | 16 | if (error is WorkerException) { |
28 | | 9 | if (command != null) error.setCommand(command); |
29 | | 5 | return error; |
30 | | 9 | } else if (error is SquadronException) { |
31 | | 5 | return error; |
32 | | 5 | } else if (error is CanceledException) { |
33 | | 2 | return error.toSquadronException(); |
34 | | 5 | } else if (error is TimeoutException) { |
35 | | 2 | return error.toSquadronException(); |
36 | | | } else { |
37 | | 9 | return WorkerException(error.toString(), stackTrace, command); |
38 | | | } |
39 | | 9 | } |
40 | | |
|
41 | | | final String message; |
42 | | |
|
43 | | | /// The exception's [StackTrace]. |
44 | | 16 | StackTrace? get stackTrace => _stackTrace; |
45 | | 0 | StackTrace? _stackTrace; |
46 | | |
|
47 | | 2 | @override |
48 | | 5 | String toString() => jsonEncode(serialize()); |
49 | | |
|
50 | | | /// Serializes the exception, i.e. returns a list of items that can cross thread boundaries. |
51 | | | List serialize(); |
52 | | |
|
53 | | | /// Deserializes a [stackTrace] if any. Returns null if no [StackTrace] is provided. |
54 | | 9 | static StackTrace? loadStackTrace(String? stackTrace) => |
55 | | 6 | (stackTrace == null) ? null : StackTrace.fromString(stackTrace); |
56 | | | } |