Skip to content

Commit 0a827da

Browse files
committed
refactor(bloc_observer): enhance state change logging
- Implement truncation for long state string representations - Prioritize 'status' property logging when available - Improve error handling when accessing 'status' property - Add fallback to detailed state info for states without 'status' - Include error logging for debugging purposes
1 parent 0d0b670 commit 0a827da

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

lib/bloc_observer.dart

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,42 @@ class AppBlocObserver extends BlocObserver {
1313
final dynamic oldState = change.currentState;
1414
final dynamic newState = change.nextState;
1515

16-
var oldStateInfo = oldState.runtimeType.toString();
17-
var newStateInfo = newState.runtimeType.toString();
16+
// Initialize state information strings.
17+
// By default, truncate the full string representation of the state
18+
// to the first 250 characters to prevent excessively long logs.
19+
var oldStateInfo = oldState.toString().substring(
20+
0,
21+
oldState.toString().length > 250 ? 250 : oldState.toString().length,
22+
);
23+
var newStateInfo = newState.toString().substring(
24+
0,
25+
newState.toString().length > 250 ? 250 : newState.toString().length,
26+
);
1827

1928
try {
20-
// Attempt to access a 'status' property if it exists
29+
// Attempt to access a 'status' property on the state objects.
30+
// Many BLoC states use a 'status' property (e.g., Loading, Success, Failure)
31+
// to represent their current lifecycle phase. If this property exists
32+
// and is not null, prioritize logging its value for conciseness.
2133
if (oldState.status != null) {
2234
oldStateInfo = 'status: ${oldState.status}';
2335
}
2436
if (newState.status != null) {
2537
newStateInfo = 'status: ${newState.status}';
2638
}
27-
} catch (_) {
28-
// If 'status' property does not exist, or is null,
29-
// or if there's any other error accessing it,
30-
// fall back to runtimeType (which is already set).
39+
} catch (e) {
40+
// This catch block handles cases where:
41+
// 1. The 'status' property does not exist on the state object (NoSuchMethodError).
42+
// 2. Accessing 'status' throws any other runtime error.
43+
// In such scenarios, the `oldStateInfo` and `newStateInfo` variables
44+
// will retain their initially truncated string representations,
45+
// providing a fallback for states without a 'status' property.
46+
// Log the error for debugging purposes, but do not rethrow to avoid
47+
// crashing the observer.
48+
log('Error accessing status property for ${bloc.runtimeType}: $e');
3149
}
3250

51+
// Log the state change, including the BLoC type and the old and new state information.
3352
log('onChange(${bloc.runtimeType}, $oldStateInfo -> $newStateInfo)');
3453
}
3554

0 commit comments

Comments
 (0)