Flutter application full-link exception processing and intelligent gray degradation system and method

CN122884810APending Publication Date: 2026-10-09JIANGLING MOTORS
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610670768.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-15
Publication Date
2026-10-09

AI Technical Summary

Technical Problem

[0004]但是上述现有技术往往存在以下缺点:1.异常信息孤立,缺乏用户操作上下文,导致难以复现,传统上报仅包含静态堆栈和设备信息,未记录异常发生前的用户操作路径、手势序列、页面状态(如flutter_user_recorder虽能录制但未与异常联动)

Benefits of technology

[0031]1.提升问题定位效率与准确性:相比传统仅上报堆栈的方案,本发明提供的操作序列现场回放功能,让开发者能直观看到用户“做了什么”才导致崩溃,极大减少了猜测成本,尤其对难以复现的偶发崩溃有奇效。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122884810A_ABST
    Figure CN122884810A_ABST
Patent Text Reader

Abstract

The application provides a Flutter application full-link exception processing and intelligent gray degradation system and method, aiming to solve the problems of incomplete exception capture, difficult scenario reproduction and slow degradation response in the prior art. The system includes modules such as exception capture and operation recording, covers multi-level exceptions through a full-level unified capture architecture, cooperates with the ring buffer module to realize exception linkage freezing to retain operation context, encapsulates structured data packets through the log packaging module, dynamically decides in combination with the server rules and local exception history through the gray degradation module, and forms a complete processing closed loop. The method is based on the system and realizes steps such as initialization, operation recording, exception processing, data reporting, degradation decision and access interception. The application can accurately reproduce the exception scenario, quickly respond to crashes, reduce user perception, reduce operation and maintenance cost, and improve application robustness.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of mobile application exception handling technology, specifically to a Flutter application end-to-end exception handling and intelligent gray-scale degradation system and method. Background Technology

[0002] Flutter, Google's open-source cross-platform mobile application development framework, has been widely adopted globally. As business complexity increases, Flutter applications may encounter various anomalies during runtime, including Dart runtime errors, native platform channel communication failures, and even engine crashes. Failure to properly handle these anomalies can directly lead to application crashes or blank screens, severely impacting user experience and application reputation.

[0003] Currently, the industry's common exception handling solutions mainly adopt the following technical means: 1. Create a sandbox environment using Dart's Zone.runZoned method and intercept uncaught App exceptions through the onError callback; 2. Register the FlutterError.onError callback to uniformly handle Framework exceptions; 3. Integrate platform SDKs (Software Development Kits) such as Firebase Crashlytics and Bugly to handle native layer crashes.

[0004] However, the aforementioned existing technologies often have the following drawbacks: 1. Anomaly information is isolated and lacks user operation context, making it difficult to reproduce. Traditional reporting only includes static stack traces and device information, without recording the user operation path, gesture sequence, or page state before the anomaly occurred (e.g., although flutter_user_recorder can record, it is not linked to the anomaly). 2. There is no corresponding gray-scale strategy when an anomaly occurs, and it can only be fixed by releasing an update. 3. Anomaly monitoring and user behavior analysis are separated, making it impossible to form an optimization loop. Anomaly logs and operation logs are recorded on different SDK platforms, making joint troubleshooting difficult. In practical applications, the aforementioned existing technologies are insufficient to meet the high robustness and maintainability requirements of Flutter applications. Summary of the Invention

[0005] To address the shortcomings of existing technologies, the purpose of this invention is to provide a Flutter application end-to-end exception handling and intelligent gray-scale degradation system and method. This system enables full-level exception capture, builds operation recording and on-site reproduction capabilities, and incorporates a user-friendly degradation and error message mechanism. When an exception occurs, it automatically displays an understandable and interactive error page and dynamically degrades to H5 or other solutions based on configuration, ensuring uninterrupted core business operations and improving user experience. Furthermore, through a dynamic configuration center, it achieves gradual scaling based on user attributes, automatically triggering degradation by combining real-time exception data and historical markers, upgrading risk control from passive response to proactive prevention, forming a complete closed loop of "exception occurrence - reduced user perception - automatic isolation - subsequent prevention."

[0006] To achieve the above-mentioned technical effects, the present invention adopts the following technical solution:

[0007] According to a first aspect of the present invention, a Flutter application end-to-end exception handling and intelligent canary degradation system is provided, comprising an exception capture module, an operation recording module, a circular buffer storage module, a log packaging module, a user-friendly error display module, a canary degradation decision module, a routing manager, and a server-side interaction module, wherein the modules work collaboratively, wherein:

[0008] The exception capture module is used for full-level exception listening and capture, covering the Dart layer, Flutter Framework layer, native platform layer and engine layer. After capturing an exception, it immediately triggers the subsequent processing flow. The exception capture module is used to capture exceptions at all levels and trigger subsequent processing.

[0009] The operation recording module is used to capture global user interaction events in a non-intrusive listening manner, generate operation records with timestamps, and write them to the circular buffer storage module in real time.

[0010] The circular buffer storage module uses a circular buffer to store user operation records and has a freeze function. After receiving the freeze command from the anomaly capture module, it instantly stops writing operation records, completely preserving all operation contexts before the anomaly occurred, and avoiding data overflow and loss.

[0011] The log packaging module is used to structurally assemble the exception information obtained by the exception capture module, the operation sequence frozen by the ring buffer storage module, and the environmental information of the system equipment to generate a complete field data packet, and report it to the server in an asynchronous manner through the server interaction module;

[0012] The user-friendly error display module is used to quickly overwrite the current application interface and display an error message page that is understandable and interactive to the user when an error occurs.

[0013] The gray-scale degradation decision module is used to dynamically determine degradation and send instructions. It can combine server-side configuration and local anomaly history to support degradation triggered by user attributes and anomaly number thresholds.

[0014] The routing manager is used to manage and intercept page routes within the application, receive degradation instructions from the gray-scale degradation decision module, and automatically redirect to the H5 alternative page or a friendly error page when the user accesses an abnormal page, thus implementing the degradation logic.

[0015] The server-side interaction module is used to implement data interaction with the server.

[0016] Optionally, the user global interaction events include clicks, swipes, and route switching.

[0017] Optionally, the subsequent processing flow includes sending a freeze command to the ring buffer storage module, calling the user-friendly error display module, and triggering the log packaging module to work.

[0018] Optionally, the error message page supports retry and return to the homepage to avoid application crashes or blank screens.

[0019] Optionally, the data interaction includes pulling the initial configuration for grayscale degradation, reporting on-site data packets, and synchronizing the anomaly handling status.

[0020] According to a second aspect of the present invention, a method for end-to-end exception handling and intelligent canary-scale degradation in Flutter applications is provided, implemented using the above-mentioned system, and includes the following specific steps:

[0021] Step S1. System initialization; When the application starts, the exception capture module, operation recording module and circular buffer storage module are initialized, and the gray-scale degradation decision module pulls the initial gray-scale configuration from the server.

[0022] Step S2. Normal user operation; The user interacts with the interface, the operation recording module captures the interaction operation events, generates operation records with timestamps, and writes them to the circular buffer storage module in real time;

[0023] Step S3. Determine if an exception has occurred; the exception capture module continuously monitors the exception status of the Dart layer, Flutter Framework layer, native platform layer and engine layer, and makes real-time judgments; if no exception has occurred, it returns to the normal user operation steps, continues to capture user operations and record them; if an exception is detected, it immediately enters the exception handling trigger step and triggers the exception handling process.

[0024] Step S4. Trigger the exception handling process; the exception capture module immediately takes over control, prevents the exception from spreading and causing the application to crash, and sends a "freeze" command to the circular buffer storage module to stop writing new operation records; call the user-friendly error display module to immediately display a transition interface of "the application has encountered a problem" to prevent a blank screen;

[0025] Step S5. Data Packaging and Reporting: The log packaging module reads the frozen operation queue from the circular buffer storage module, obtains exception information from the exception capture module, obtains device environment information from the system, assembles it into a complete field data packet, and reports it to the server asynchronously.

[0026] Step S6. Gray-scale degradation decision; The gray-scale degradation decision module determines whether the current page should be marked as "abnormal" based on the reported exception type, occurrence frequency, and server configuration. If it is determined that the current page has high-frequency exceptions and needs to be downgraded, the degradation mark of the page is stored locally, and the degradation instruction is sent to the routing manager to notify the routing manager to intercept access to the page. If it is determined that no degradation is needed, no mark is made, and the application continues to run normally.

[0027] Step S7. Subsequent user actions; When the user tries to open the same page again, the route interceptor will trigger the gray-scale degradation decision module. This module detects the local degradation flag and directly jumps to the pre-prepared H5 alternative page or displays a friendly error page with retry options, thereby avoiding entering the unstable Flutter native page again.

[0028] Optionally, the initial grayscale configuration in step S1 includes the degradation threshold, the scaling ratio, and the H5 alternative page address.

[0029] Optionally, the exception information in step S5 includes exception type, exception stack, and exception location; the device environment information includes device model, system version, application version, and network status.

[0030] Compared with the prior art, the present invention has the following beneficial effects:

[0031] 1. Improve the efficiency and accuracy of problem localization: Compared with the traditional solution that only reports the stack trace, the operation sequence playback function provided by this invention allows developers to see intuitively what the user "did" that caused the crash, greatly reducing the cost of guessing, and is especially effective for sporadic crashes that are difficult to reproduce.

[0032] 2. Reduced Operational Costs and Risks: Through a canary rollout strategy, most crashes introduced by the new version's code can be "closed" or downgraded without an emergency release. This saves the development team on hotfix and release costs and avoids the inconvenience caused to users by forced upgrades.

[0033] 3. Enhance application robustness and user trust: The user-friendly error display module replaces the system's default crash or ANR dialog box, providing users with clear feedback and operation paths.

[0034] 4. Forming a data-driven optimization loop: The deep integration of anomaly monitoring (crash scenario) and user behavior analysis (operation sequence) provides data support for product managers and developers. It allows analysis of "which operation path is most likely to cause a crash," enabling targeted refactoring or interaction optimization in subsequent versions. Attached Figure Description

[0035] Other features, objects, and advantages of the present invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings:

[0036] Figure 1 This is a flowchart of the method described in Example 2. Detailed Implementation

[0037] To make the objectives, technical solutions, and advantages of the embodiments of this application clearer, the technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. The components of the embodiments of this application described and shown in the accompanying drawings can generally be arranged and designed in various different configurations.

[0038] Therefore, the following detailed description of the embodiments of this application provided in the accompanying drawings is not intended to limit the scope of the claimed application, but merely to illustrate selected embodiments of the application. All other embodiments obtained by those skilled in the art based on the embodiments of this application without inventive effort are within the scope of protection of this application.

[0039] It should be noted that similar reference numerals and letters in the following figures indicate similar items. Therefore, once an item is defined in one figure, it does not need to be further defined and explained in subsequent figures. Furthermore, all directional indications (such as up, down, left, right, front, back, bottom, etc.) in this application are only used to explain the relative positional relationships and movements between components in a specific orientation (as shown in the figures). If the specific orientation changes, the directional indication will also change accordingly. Furthermore, descriptions involving "first," "second," etc., in this application are for descriptive purposes only and should not be construed as indicating or implying their relative importance or implicitly specifying the number of technical features indicated.

[0040] Example 1

[0041] This embodiment provides a Flutter application end-to-end exception handling and intelligent canary deployment system. It adopts a modular architecture design, where each module functions independently yet collaboratively. Through multi-module collaboration, end-to-end exception handling and intelligent canary deployment are achieved. The specific system architecture and module functions are as follows:

[0042] (I) Overall System Architecture

[0043] This system includes an exception capture module, an operation recording module, a circular buffer storage module, a log packaging module, a user-friendly error display module, a canary degradation decision-making module, a routing manager, and a server-side interaction module. These modules work together to form a complete exception handling and canary degradation system. The specific functions of each module are as follows:

[0044] 1. Exception Capture Module: The core is used for full-level exception listening and capture, covering the Dart layer, FlutterFramework layer, native platform layer, and engine layer. After an exception is captured, the subsequent processing flow is triggered immediately, including sending a freeze command to the circular buffer storage module, calling the friendly error display module, and triggering the log packaging module to work, ensuring that no exceptions are missed and that the response is fast. Unlike existing solutions that only capture Dart or Framework layer exceptions, this embodiment builds a full-link capture system covering Dart runtime, Framework construction, native platform, and engine crashes by combining runZonedGuarded, Flutter Error.on Error, and native platform channel listening.

[0045] 2. Operation Recording Module: Employs a non-intrusive listening mechanism to monitor global user interaction events (clicks, swipes, route switching, etc.), generate timestamped operation records, and write them to the circular buffer storage module in real time. This eliminates the need for separate configuration on each page, achieving complete recording of the user's operation path.

[0046] 3. Ring Buffer Storage Module: The module uses a ring buffer to store user operation records. It has a freeze function, which can instantly stop writing when an exception occurs, fully preserving the operation context before the exception occurred, avoiding data overflow and loss, and ensuring the integrity of the operation sequence. Its core design refers to the basic management logic of the ring buffer, while adding a linkage mechanism with exception handling, which is different from the existing technical solutions that only optimize buffer management.

[0047] 4. Log Packaging Module: This module is used to structurally assemble abnormal information, frozen operation sequences, and equipment environment information to generate complete field data packets. It supports asynchronous reporting to the server and provides standardized data support for anomaly analysis and scene playback.

[0048] 5. User-friendly error display module: When an error occurs, quickly overwrite the current application interface to display an error message page that is understandable and interactive to the user, supporting operations such as retry and returning to the home page, avoiding application white screen and crashes, and improving user experience;

[0049] 6. Gray-scale degradation decision module: As the core decision unit, it adopts the singleton pattern design and combines server-side dynamic configuration and local anomaly history marking to realize dynamic judgment of gray-scale degradation. It supports logic such as volume increase based on user attributes and triggering degradation based on anomaly number threshold, which is different from the existing gray-scale release scheme that only relies on server-side static rules.

[0050] 7. Route Manager: Responsible for managing and intercepting page routes within the application, receiving instructions from the gray-scale degradation decision module, and automatically redirecting users to H5 alternative pages or user-friendly error pages when they access abnormal pages, thus implementing the degradation logic and ensuring the continuity of core business.

[0051] 8. Server-side interaction module: Responsible for data interaction with the server, including pulling the initial configuration for gray-scale degradation, reporting on-site data packets, and synchronizing the status of exception handling, providing stable data transmission support for client-side gray-scale decision-making and server-side scenario playback.

[0052] (II) Core Module Technical Implementation and Code Analysis

[0053] The technical implementation of each core module of this system is based on the features of the Flutter framework and developed in conjunction with the Dart language, ensuring complete functionality and feasibility. The following is a detailed explanation with reference to core code snippets (only key logic is shown, not the complete code):

[0054] 1. Operation recording module implementation

[0055] This module adopts a singleton pattern design, captures global user interaction events through a non-intrusive listening mechanism, generates timestamped operation records, and writes them to a circular buffer storage module. The core code is as follows:

[0056] / / / Operation recorder, non-intrusive listening to global interaction events

[0057] class OperationRecorder {

[0058] static final OperationRecorder _instance = OperationRecorder._internal();

[0059] factory OperationRecorder() => _instance;

[0060] OperationRecorder._internal();

[0061] RingBuffer <operationrecord>? _buffer;

[0062] bool _isInitialized = false;

[0063] void init(RingBuffer <operationrecord>buffer) {

[0064] If (_isInitialized) return;

[0065] _buffer = buffer;

[0066] _isInitialized = true;

[0067] / / Listen for global pointer events (click, swipe)

[0068] _setupGlobalPointerListener();

[0069] / / Listen for route changes

[0070] _setupRouteListener();

[0071] }

[0072] void _setupGlobalPointerListener() {

[0073] / / Utilizing the observer mechanism of WidgetsBinding

[0074] WidgetsBinding.instance.addObserver(_PointerEventObserver(this));

[0075] }

[0076] void _setupRouteListener() {

[0077] / / Inject via MaterialApp's navigatorObservers

[0078] / / In actual use, you need to add _RouteObserver to the navigatorObservers of the application's root widget.

[0079] }

[0080] void recordTap(String targetId, Offset localPosition) {

[0081] if (_buffer == null) return;

[0082] final record = OperationRecord(

[0083] type: 'tap',

[0084] targetId: targetId,

[0085] parameters: {'x': localPosition.dx, 'y': localPosition.dy},

[0086] timestamp: DateTime.now(), );

[0088] _buffer!.add(record);

[0089] }

[0090] void recordScroll(String targetId, double offset) {

[0091] if (_buffer == null) return;

[0092] final record = OperationRecord(

[0093] type: 'scroll',

[0094] targetId: targetId,

[0095] parameters: {'offset': offset},

[0096] timestamp: DateTime.now(), );

[0098] _buffer!.add(record);

[0099] }

[0100] void recordRouteChange(String fromRoute, String toRoute) {

[0101] if (_buffer == null) return;

[0102] final record = OperationRecord(

[0103] type: 'route',

[0104] targetId: 'navigator',

[0105] parameters: {'from': fromRoute, 'to': toRoute},

[0106] timestamp: DateTime.now(), );

[0108] _buffer!.add(record);

[0109] }

[0110] }

[0111] The operation recording module adopts a singleton pattern to ensure that only one instance exists during application operation, avoiding duplicate listening and data corruption. It listens to global pointer events through the WidgetsBinding observer mechanism to achieve non-intrusive capture of user clicks, swipes, and other operations without the need for separate configuration on each page. It listens for page transitions through the route observer to record the complete user operation path. All operation records include type, target identifier, parameters, and timestamp to ensure the integrity of the operation context and provide accurate data for subsequent scene playback. Operation records are written to the circular buffer storage module in real time to achieve temporary data storage and fast retrieval.

[0112] 2. Implementation of the exception handling module

[0113] This module also uses the singleton pattern and is responsible for listening to and catching exceptions at all levels, triggering the exception handling process. The core code is as follows:

[0114] / / / Full-level exception catcher

[0115] class ExceptionCatcher {

[0116] static final ExceptionCatcher _instance = ExceptionCatcher._internal();

[0117] factory ExceptionCatcher() => _instance;

[0118] ExceptionCatcher._internal();

[0119] RingBuffer? _buffer;

[0120] late LogPacker _logPacker;

[0121] void init(RingBuffer buffer) {

[0122] _buffer = buffer;

[0123] _logPacker = LogPacker();

[0124] / / 1. Catching unhandled exceptions in the Dart layer

[0125] runZonedGuarded(() {

[0126] / / Application startup code

[0127] }, (error, stack) {

[0128] _handleException(error, stack, 'dart_uncaught');

[0129] });

[0130] / / 2. Catching Flutter Framework layer exceptions

[0131] FlutterError.onError = (FlutterErrorDetails details) {

[0132] _handleException(details.exception, details.stack, 'framework');

[0133] / / Avoid the framework's default fatal handling causing the application to crash

[0134] if (kReleaseMode) {

[0135] / / Display a user-friendly error page

[0136] _showGracefulError(details.exception);

[0137] }

[0138] };

[0139] / / 3. Native platform exception monitoring (receiving native crash signals via MethodChannel)

[0140] _setupNativeChannelListener();

[0141] }

[0142] void _handleException(dynamic error, StackTrace? stack, Stringsource) {

[0143] / / Freeze the circular buffer

[0144] if (_buffer != null && !_buffer!.isFrozen) {

[0145] _buffer!.freeze();

[0146] }

[0147] / / Package and report

[0148] final operations = _buffer?.getAll() ?? [];

[0149] _logPacker.packAndReport(

[0150] exception: error,

[0151] stackTrace: stack,

[0152] source: source,

[0153] operations: operations, );

[0155] }

[0156] void _showGracefulError(dynamic error) {

[0157] / / Use a user-friendly error display module to overwrite the current page

[0158] WidgetsBinding.instance.addPostFrameCallback((_) {

[0159] / / Get the current navigator context and push the error page

[0160] / / In the specific implementation, it can be obtained through GlobalKey

[0161] });

[0162] }

[0163] void _setupNativeChannelListener() {

[0164] / / Example: Receiving native crash signals via MethodChannel

[0165] const channel = MethodChannel('com.app.crash_listener');

[0166] channel.setMethodCallHandler((call) async {

[0167] if (call.method == 'onNativeCrash') {

[0168] final info = call.arguments as Map;

[0169] _handleException(info['error'], null, 'native');

[0170] }

[0171] return null;

[0172] });

[0173] }

[0174] }

[0175] The exception capture module implements full-level exception capture in three ways: unhandled exceptions in the Dart layer, exceptions in the Flutter Framework layer, and exceptions in the native platform layer, ensuring no exceptions are missed. After an exception is captured, the circular buffer storage module is immediately frozen to prevent operation records from being overwritten and to fully preserve the operation context before the exception occurred. At the same time, the user-friendly error display module is called to display an interactive error page in release mode to prevent application crashes. Finally, the log packaging module packages and reports exception information, operation sequences, and other data to support server-side analysis. Native platform exceptions communicate with the native layer through MethodChannel to achieve unified capture and handling of cross-platform exceptions.

[0176] 3. Implementation of the grayscale degradation decision module

[0177] This module is a singleton and is responsible for making dynamic decisions regarding canary deployments based on server-side configuration and local exception history. The core code is as follows:

[0178] / / / Gray-scale degradation decision-maker

[0179] class GrayDecision {

[0180] static final GrayDecision _instance = GrayDecision._internal();

[0181] factory GrayDecision() => _instance;

[0182] GrayDecision._internal();

[0183] static const String _PREF_DEGRADED_PAGES = 'degraded_pages';

[0184] static const String _PREF_CRASH_COUNT_PREFIX = 'crash_count_';

[0185] Future <bool>shouldDegrade(String pageRoute) async {

[0186] / / 1. Check local downgrade flags (caused by historical anomalies)

[0187] if (await _isLocallyDegraded(pageRoute)) {

[0188] return true;

[0189] }

[0190] / / 2. Retrieve server-side canary deployment configuration (Example: via Remote Config)

[0191] final serverConfig = await _fetchServerConfig(pageRoute);

[0192] if (serverConfig == null) return false;

[0193] / / 3. Make decisions based on the server-side deployment ratio

[0194] final ratio = serverConfig['ratio'] ?? 0.0; / / 0.0 ~ 1.0

[0195] if (ratio <= 0.0) return false;

[0196] if (ratio >= 1.0) return true;

[0197] / / Determine whether to include the grayscale group based on the user ID hash.

[0198] final userId = await _getUserId();

[0199] final hash = userId.hashCode.abs() % 100;

[0200] return hash < (ratio * 100);

[0201] }

[0202] Future <bool>_isLocallyDegraded(String pageRoute) async {

[0203] final prefs = await SharedPreferences.getInstance();

[0204] final degradedList = prefs.getStringList(_PREF_DEGRADED_PAGES) ??[];

[0205] return degradedList.contains(pageRoute);

[0206] }

[0207] / / / Mark a page that needs to be degraded (e.g., after multiple crashes).

[0208] Future <void>markDegraded(String pageRoute, {int durationHours =24}) async {

[0209] final prefs = await SharedPreferences.getInstance();

[0210] final degradedList = prefs.getStringList(_PREF_DEGRADED_PAGES) ??[];

[0211] if (!degradedList.contains(pageRoute)) {

[0212] degradedList.add(pageRoute);

[0213] await prefs.setStringList(_PREF_DEGRADED_PAGES, degradedList);

[0214] }

[0215] / / An expiration timer can be set; the marker will be automatically cleared after durationHours.

[0216] }

[0217] / / / Clear the degradation flag

[0218] Future <void>clearDegraded(String pageRoute) async {

[0219] final prefs = await SharedPreferences.getInstance();

[0220] final degradedList = prefs.getStringList(_PREF_DEGRADED_PAGES) ??[];

[0221] if (degradedList.contains(pageRoute)) {

[0222] degradedList.remove(pageRoute);

[0223] await prefs.setStringList(_PREF_DEGRADED_PAGES, degradedList);

[0224] }

[0225] }

[0226] / / / Records the number of page errors (used to trigger automatic degradation)

[0227] Future <void>recordCrash(String pageRoute) async {

[0228] final prefs = await SharedPreferences.getInstance();

[0229] final key = _PREF_CRASH_COUNT_PREFIX + pageRoute;

[0230] int count = prefs.getInt(key) ?? 0;

[0231] count++;

[0232] await prefs.setInt(key, count);

[0233] / / Threshold judgment, for example, if it crashes 3 times within 5 minutes, it will automatically degrade.

[0234] if (count >= 3) {

[0235] await markDegraded(pageRoute);

[0236] }

[0237] }

[0238] Future <Map<String, dynamic> ?> _fetchServerConfig(String pageRoute)async {

[0239] / / Actually obtained via HTTP request or Firebase Remote Config

[0240] / / Example returned: {'ratio': 0.1, 'h5_url': 'https: / / xxx'}

[0241] return null;

[0242] }

[0243] Future <string>_getUserId() async {

[0244] final prefs = await SharedPreferences.getInstance();

[0245] return prefs.getString('user_id') ?? 'anonymous';

[0246] }

[0247] }

[0248] The canary release degradation decision module adopts a decision logic of "local marking first + server-side configuration supplement" to ensure the real-time nature and flexibility of degradation decisions. Local marking is triggered based on the page crash count threshold. By default, three crashes within 5 minutes will automatically mark the page as degraded. The mark has an expiration period to avoid long-term degradation affecting user experience. Server-side configuration supports proportional scaling, using user ID hash values ​​to achieve precise scaling based on user attributes, which is different from existing canary release solutions that only rely on static server-side rules. It provides methods for adding and clearing degradation marks, supporting rapid recovery after anomaly repair. At the same time, it records the number of page crashes, forming a closed-loop degradation decision mechanism.

[0249] 4. Router Manager Implementation (Core of Degradation Interception)

[0250] The route manager is responsible for managing and intercepting page routes within the application, receiving instructions from the canary deployment decision module, and intercepting redirects to abnormal pages. The core code is as follows:

[0251] Routing integration and degradation interception examples

[0252] class AppRouter {

[0253] static Future<Widget?> handleRoute(RouteSettings settings) async {

[0254] final pageRoute = settings.name ?? ' / ';

[0255] final shouldDegrade = await GrayDecision().shouldDegrade(pageRoute);

[0256] if (shouldDegrade) {

[0257] / / Downgrade to an H5 page or a user-friendly error page

[0258] return _buildFallbackPage(pageRoute);

[0259] }

[0260] / / Normal return to the native Flutter page

[0261] return _buildNormalPage(pageRoute);

[0262] }

[0263] static Widget _buildFallbackPage(String route) {

[0264] / / Load alternative H5 pages via WebView

[0265] return H5Page(route);

[0266] }

[0267] static Widget _buildNormalPage(String route) {

[0268] / / Return to the actual page based on the route

[0269] switch (route) {

[0270] case ' / home':

[0271] return HomePage();

[0272] default:

[0273] return UnknownPage();

[0274] }

[0275] }

[0276] }

[0277] The route manager intercepts all page access requests through the handleRoute method. It first calls the canary degradation decision module to determine whether degradation is needed. If degradation is needed, it loads the H5 alternative page corresponding to the current route through WebView to ensure that the core business can be accessed normally. If degradation is not needed, it returns to the native Flutter page normally. This module implements the degradation logic and combines canary decision with route navigation to form a complete degradation execution chain.

[0278] Example 2

[0279] like Figure 1 As shown, this embodiment provides a method for end-to-end exception handling and intelligent canary degradation in Flutter applications. Based on the system implementation of Embodiment 1 above, it follows the logic of "initialization - normal operation - exception triggering - processing and reporting - degradation decision - subsequent interception" to achieve end-to-end exception capture, processing, and intelligent canary degradation. The specific process steps are as follows:

[0280] 1. System initialization steps: When the application starts, the exception capture module, operation recording module and circular buffer storage module are automatically initialized, and the parameter configuration and function readiness of each module are completed. At the same time, the gray-scale degradation decision module pulls the initial gray-scale configuration from the server through the server interaction module, including the degradation threshold, the scale ratio, the H5 alternative page address, etc., and stores it locally to provide a basis for subsequent decisions.

[0281] 2. Normal user operation steps: When users interact with the application interface (including clicks, swipes, page switching, etc.), the operation recording module captures these interaction events through a non-intrusive listening mechanism, generates operation records containing operation type, target identifier, operation parameters, and timestamps, and writes them to the circular buffer storage module in real time. The circular buffer storage module stores the records in a circular queue according to the rules of the circular queue to ensure the continuity of the operation records and avoid data overflow.

[0282] 3. Exception detection steps: The exception capture module continuously monitors for exceptions in the Dart layer, Flutter Framework layer, native platform layer, and engine layer, and makes real-time judgments. If no exception occurs, it returns to the normal user operation steps and continues to capture and record user operations. If an exception is detected, it immediately enters the exception handling trigger step and triggers the exception handling process.

[0283] 4. Exception Handling Triggering Steps: The exception capture module immediately takes over application control, preventing the exception from spreading by intercepting the exception propagation mechanism and avoiding a direct application crash. Simultaneously, it sends a "freeze" command to the circular buffer storage module. Upon receiving the command, the circular buffer storage module instantly stops writing new operation records, completely preserving all operation context before the exception occurred, ensuring the integrity of the operation sequence. Furthermore, the exception capture module calls the user-friendly error display module, immediately displaying a transitional message "Application encountered a problem" on the application interface, along with interactive buttons such as retry and return to the homepage, preventing a blank screen and improving user experience. In this step, the system continuously and non-intrusively records user operations into a circular queue. When an exception occurs, this queue can be instantly "frozen," thus completely preserving all operation context before the exception occurred. This is the technical foundation for achieving "scene replay."

[0284] 5. Data Packaging and Reporting Steps: After the log packaging module is triggered, it reads the frozen operation queue from the circular buffer storage module, obtains exception information (including exception type, exception stack, exception location, etc.) from the exception capture module, and obtains device environment information (including device model, system version, application version, network status, etc.) from the system. These three parts of information are then structurally assembled according to a preset format to generate a complete on-site data packet. Subsequently, the on-site data packet is asynchronously reported to the server through the server-side interaction module to avoid affecting the current exception handling process of the application. The server receives and stores the data packet, providing data support for subsequent scene playback and exception analysis. The structured packaging and reporting protocol for exception scenarios in this step defines and implements a data packaging format specifically for exception analysis. This format mandates the associative encapsulation of the "operation sequence in the circular buffer," "exception stack," and "device / application status." This structured on-site data packet is a prerequisite for the effective operation of the server-side playback engine.

[0285] 6. Gray-scale Degradation Decision-Making Steps: The gray-scale degradation decision-making module dynamically determines degradation based on the reported anomaly type and frequency, combined with the server's initial configuration and historical anomaly markers stored locally. If it determines that the current page has high-frequency anomalies and needs degradation, it stores the page's degradation marker locally (with a validity period set, defaulting to 24 hours) and sends the degradation command to the routing manager, notifying the routing manager to intercept access to the page. If it determines that degradation is not necessary, no marker is set, and the application continues to run normally. The gray-scale degradation decision-making method combining real-time anomalies and historical markers provided in this step not only relies on the static gray-scale rules issued by the server but also incorporates the page's anomaly history stored locally (such as crash frequency and error type), performing dynamic judgment locally on the client. This enables the degradation strategy to respond in real time to sudden large-scale crashes, achieving "self-repair."

[0286] 7. Subsequent user actions: When a user attempts to open the same page marked as downgraded again, the route interceptor of the route manager immediately triggers the gray-scale degradation decision module. This module detects the locally stored degradation mark and that the mark has not expired. It directly instructs the route manager to jump to a pre-configured H5 alternative page or display a user-friendly error page with retry options, thereby preventing the user from entering the unstable Flutter native page again and ensuring that core business can be accessed normally. If the degradation mark has expired or no degradation mark is detected, the Flutter native page is loaded normally.

[0287] The complete closed-loop processing flow provided in this embodiment, from anomaly capture to friendly degradation, connects the aforementioned independent modules (capture, recording, decision-making, and display) into a complete, stateful processing flow. In particular, once the degradation decision takes effect, the system can persistently mark the error and directly provide an alternative solution on the user's next visit, forming a closed loop of "anomaly occurrence -> reduced user perception -> automatic isolation -> subsequent prevention".

[0288] The specific embodiments of the present invention have been described above. Based on the above description, those skilled in the art can make various changes and modifications without departing from the technical concept of the present invention.< / string> < / void> < / void> < / void> < / bool> < / bool> < / operationrecord> < / operationrecord>

Claims

1. A Flutter application end-to-end exception handling and intelligent canary-scale degradation system, characterized in that, It includes modules for exception handling, operation recording, circular buffer storage, log packaging, user-friendly error display, gray-scale degradation decision-making, routing manager, and server-side interaction. These modules work together, including: The exception capture module is used for full-level exception listening and capture, covering the Dart layer, Flutter Framework layer, native platform layer and engine layer. After capturing an exception, it immediately triggers the subsequent processing flow. The exception capture module is used to capture exceptions at all levels and trigger subsequent processing. The operation recording module is used to capture global user interaction events in a non-intrusive listening manner, generate operation records with timestamps, and write them to the circular buffer storage module in real time. The circular buffer storage module uses a circular buffer to store user operation records and has a freeze function. After receiving the freeze command from the anomaly capture module, it instantly stops writing operation records, completely preserving all operation contexts before the anomaly occurred, and avoiding data overflow and loss. The log packaging module is used to structurally assemble the exception information obtained by the exception capture module, the operation sequence frozen by the ring buffer storage module, and the environmental information of the system equipment to generate a complete field data packet, and report it to the server in an asynchronous manner through the server interaction module; The user-friendly error display module is used to quickly overwrite the current application interface and display an error message page that is understandable and interactive to the user when an error occurs. The gray-scale degradation decision module is used to dynamically determine degradation and send instructions. It can combine server-side configuration and local anomaly history to support degradation triggered by user attributes and anomaly number thresholds. The routing manager is used to manage and intercept page routes within the application, receive degradation instructions from the gray-scale degradation decision module, and automatically redirect to the H5 alternative page or a friendly error page when the user accesses an abnormal page, thus implementing the degradation logic. The server-side interaction module is used to implement data interaction with the server.

2. A method for end-to-end exception handling and intelligent canary-scale degradation in Flutter applications, characterized in that, The system described in claim 1 includes the following specific steps: Step S1. System initialization; When the application starts, initialize the exception capture module, operation recording module and circular buffer storage module, and the gray-scale degradation decision module pulls the initial gray-scale configuration from the server. Step S2. Normal user operation; The user interacts with the interface, the operation recording module captures the interaction operation events, generates operation records with timestamps, and writes them to the circular buffer storage module in real time; Step S3. Determine if an anomaly has occurred; The exception capture module continuously monitors the Dart layer, Flutter Framework layer, native platform layer and engine layer for exceptions and makes real-time judgments. If no exception occurs, it returns to the user's normal operation steps and continues to capture and record user operations. If an exception is detected, it immediately enters the exception handling trigger step and triggers the exception handling process. Step S4. Trigger the exception handling process; The exception capture module immediately takes over control, prevents the exception from spreading and causing the application to crash, and sends a "freeze" command to the circular buffer storage module to stop writing new operation records; it also calls the user-friendly error display module to immediately display a transition interface saying "The application has encountered a problem" to prevent a blank screen. Step S5. Data Packaging and Reporting: The log packaging module reads the frozen operation queue from the circular buffer storage module, obtains exception information from the exception capture module, obtains device environment information from the system, assembles it into a complete field data packet, and reports it to the server asynchronously. Step S6. Gray-scale degradation decision; The gray-scale degradation decision module determines whether the current page should be marked as "abnormal" based on the reported anomaly type, occurrence frequency, and server configuration. If it is determined that the current page has high frequency of anomalies and needs to be downgraded, the downgrade flag for the page is stored locally, and the downgrade instruction is sent to the routing manager to notify the routing manager to block access to the page; if it is determined that no downgrade is needed, no flag is set, and the application continues to run normally. Step S7. Subsequent user actions; When the user tries to open the same page again, the route interceptor will trigger the gray-scale degradation decision module. This module detects the local degradation flag and directly jumps to the pre-prepared H5 alternative page or displays a friendly error page with retry options, thereby avoiding entering the unstable Flutter native page again.

3. The system according to claim 1, characterized in that, The user-wide interaction events include clicks, swipes, and route switching.

4. The system according to claim 1, characterized in that, The subsequent processing flow includes sending a freeze command to the circular buffer storage module, calling the user-friendly error display module, and triggering the log packaging module to work.

5. The system according to claim 1, characterized in that, The error message page supports retrying and returning to the homepage, preventing the application from displaying a blank screen or crashing.

6. The system according to claim 1, characterized in that, The data interaction includes pulling the initial configuration for grayscale degradation, reporting on-site data packets, and synchronizing the status of abnormal handling.

7. The method according to claim 2, characterized in that, The initial grayscale configuration in step S1 includes the degradation threshold, the scaling ratio, and the alternative H5 page addresses.

8. The method according to claim 2, characterized in that, The exception information in step S5 includes exception type, exception stack, and exception location; the device environment information includes device model, system version, application version, and network status.