A Front-End Intelligent Anomaly Protection and Self-Healing Method and Device Based on Vue3 and Vite

By combining build-time instrumentation and runtime multi-layered wrapping with strategic self-healing, the problem of insufficient exception detection coverage in web front-end applications is solved, enabling statement-level exception capture and automatic repair, thereby improving application stability and user experience.

CN121681332BActive Publication Date: 2026-04-21YUNNAN PROVINCIAL BIG DATA CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
YUNNAN PROVINCIAL BIG DATA CO LTD
Filing Date
2026-02-06
Publication Date
2026-04-21

AI Technical Summary

Technical Problem

Existing technologies cannot achieve fine-grained anomaly detection and real-time self-healing in web front-end applications. In particular, they have low capture rates and lack automatic repair capabilities in scenarios such as dynamic module loading and asynchronous tasks, resulting in insufficient application stability and availability.

Method used

The front-end intelligent exception protection and self-healing method based on Vue3 and Vite uses a build-time instrumentation subsystem to protect and instrument source files line by line or block by block. Combined with a runtime high-order wrapper and a strategy-based self-healing engine, it achieves statement-level exception capture and automatic repair.

Benefits of technology

It significantly improved the anomaly detection rate, reduced the probability of white screen and function interruption, shortened the fault repair time, achieved automated fault self-healing and reduced operation and maintenance costs, and improved the overall availability of the application and user experience.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121681332B_ABST
    Figure CN121681332B_ABST
Patent Text Reader

Abstract

This invention relates to a front-end intelligent anomaly protection and self-healing method and device based on Vue3 and Vite, belonging to the field of front-end application runtime security and self-healing technology. The device includes a build-time instrumentation subsystem, a runtime subsystem, a strategy-based self-healing engine, an action executor, and a feedback evaluation module. The method includes build-time instrumentation, front-end runtime monitoring; anomaly reporting and policy distribution; and automatic retries, hot patching, functional degradation, or safety rollback based on the policies. Technically, this invention achieves high-coverage front-end anomaly detection, low-interruption-rate fault-tolerant operation, automated fault self-healing, and quantifiable reduction in operational costs.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to a front-end intelligent anomaly protection and self-healing method and device based on Vue3 and Vite, belonging to the field of front-end application runtime security and self-healing technology. Background Technology

[0002] Currently, anomaly monitoring and fault recovery for web front-end applications in production environments mainly rely on the following technical methods:

[0003] 1. Global Error Handling. A typical approach is to listen for global exceptions in `window.onerror`, `window.addEventListener('error')`, and `window.addEventListener('unhandledrejection')` to achieve basic error reporting. Limitations: This method only triggers when the exception has bubbled up globally, and cannot fine-grainedly identify component-level, function-level, or specific statement-level runtime errors. Its ability to handle dynamic module loading and asynchronous tasks is limited. Testing showed that common solutions achieved an exception handling rate of approximately 58% for dynamic modules and approximately 52% for asynchronous tasks in our internal benchmark tests, which is insufficient for high-availability scenarios.

[0004] 2. Framework-built error boundaries. For example, Vue and React provide ErrorBoundary or errorCaptured hooks, which can intercept exceptions and handle them in case of component rendering failures. Drawbacks: Developers need to explicitly write boundary logic in each critical component, resulting in high maintenance costs, and it cannot cover exceptions in dynamically generated code or third-party dependencies during the build process.

[0005] 3. Log monitoring and external alerting systems. The industry commonly integrates cloud-based monitoring platforms such as Sentry and Fundebug for log collection and alert push notifications. Limitations: Analysis is only possible after the fact; it cannot isolate or automatically repair errors in real-time during front-end runtime, nor can it guarantee continued application availability under severe anomalies. For example, while existing technologies like Sentry can provide real-time alerts, they lack automatic repair capabilities.

[0006] 4. Code-level redundancy and manual fault tolerance. Some teams manually wrap try / catch blocks or write higher-order function wrappers at critical logic points to enhance robustness. Drawbacks: Lack of a unified automated solution; manual addition of try / catch blocks is prone to omissions and is difficult to maintain dynamically.

[0007] 5. Build-phase detection and unit testing. Modern build tools (such as Vite and Webpack) can detect syntax or type errors during compilation, and CI processes can also execute unit tests. Limitations: These measures can only detect compile-time issues and cannot capture dynamic exceptions that occur during production.

[0008] Existing methods often only cover the "detection" or "reporting" stages, lacking an integrated closed loop of detection-isolation-repair-backtracking. Statement-level and function-level protection is insufficient: current technologies struggle to automatically instrument each statement and function body during the build phase, leaving exceptions that may still interrupt subsequent logic. Coverage for dynamic modules and asynchronous tasks is inadequate: traditional global capture mechanisms have limited capture rates in scenarios such as asynchronous module loading, dynamic imports, scheduled tasks, and event callbacks. Self-healing capabilities are lacking: most solutions only log or report alerts after an exception occurs, lacking self-healing strategies such as automatic retries, degraded rendering, and dynamic patching (Hot Patch). For example, in complex interaction and hot-reload scenarios, single-page applications (SPAs) built with Vue3 / Vite may experience blank pages or event listener failures if syntax errors or third-party library exceptions exist during initialization. Currently, there is no unified, industry-wide front-end solution that can automatically inject code, monitor in real-time, and self-heal.

[0009] In summary, existing technologies cannot meet the high requirements of modern front-end applications for real-time anomaly detection, automatic repair, and continuous availability. There is an urgent need for an automated anomaly detection and self-healing technology that integrates the build and runtime phases to improve the stability and reliability of web front-end applications in production environments. Summary of the Invention

[0010] This invention provides a front-end intelligent exception protection and self-healing method and device based on Vue3 and Vite to solve technical problems in the prior art, such as insufficient runtime exception detection coverage, delayed location and repair, low coverage of dynamic / third-party code, and semantic risks easily introduced by instrumentation during the build period.

[0011] The technical solution of this invention is: a front-end intelligent anomaly protection and self-healing device based on Vue3 and Vite, the device comprising:

[0012] The build-time instrumentation subsystem is located within the build toolchain. It is used to parse and rewrite source files, analyze abstract syntax trees, and perform line-by-line or block-by-block protection instrumentation on top-level and function body statements within a controllable range. It handles safe variable hoisting and sequential initialization of top-level variables, and outputs the generated code package and source code mapping file after instrumentation to ensure the traceability of runtime debugging and error location.

[0013] Runtime subsystem: Provides higher-order wrappers, Vue plugins / directives, error reporting clients, local strategy caching, and lightweight decision executors; enables runtime patching mechanisms for critical browser application programming interfaces as needed, and extends the scope of exception handling through function proxies or hook injection.

[0014] Strategic self-healing engine: used for policy management, matching and distribution, providing auditable action distribution and rollback mechanisms, and optimizing policies based on the feedback evaluation data; policy instructions use ECDSA-based digital signatures, and the client performs public key verification before execution;

[0015] Action executor and feedback evaluation module: used to perform retries, local degradation, isolation, function switch mechanism switching, controlled hot patching actions, monitor the effect of actions, and send back the evaluation results to complete the closed loop.

[0016] Furthermore, the construction-phase piling subsystem includes the following functions:

[0017] (1) Triggering and range control:

[0018] The triggering conditions are: based on file matching rules and supporting explicit comment switches for canary deployment and rollback control; configuration items include variable promotion options, processing-only options, reporter, and debug switch;

[0019] (2) SFC and script positioning:

[0020] The Vue SFC parser is used to extract script setting syntax, standard script syntax content, and source code offsets, which are then precisely replaced in the original .vue text. The parser is used to parse the script into an abstract syntax tree (AST), with position and range information enabled to support precise rewriting and the generation of source code mapping files.

[0021] (3) Perform security analysis on each statement node based on semantic security policy:

[0022] During syntax tree traversal, the build-time instrumentation subsystem performs security analysis on each statement node based on a semantic safety strategy. This semantic safety strategy refers to determining, before instrumentation, whether the execution context of the target statement can be rewritten or wrapped through static semantic judgment. Specifically, when the following statement nodes are detected, the build-time instrumentation subsystem will skip automatic instrumentation according to a conservative strategy:

[0023] A variable declaration statement that declares a target that is not an identifier;

[0024] Statements that include dynamic evaluation, dynamic scoping, or generator functions;

[0025] Import, export, and class declaration statements;

[0026] For skipped nodes, their syntax position information is recorded for targeted verification during the manual review stage. This strategy ensures that the instrumented code remains consistent with the original semantics at runtime, avoiding potential logical errors caused by rewriting.

[0027] (4) Top-level variable hoisting and sequential initialization:

[0028] Under the condition of meeting safety requirements, collect the top-level variable names that can be promoted and declare them at the beginning of the script. At the same time, insert the protected version of the initialization statement of each variable in the original order of the source code at the original declaration position.

[0029] For constant declarations or situations that may trigger the temporal dead zone, instead of splitting variable hoisting, the initialization statement is wrapped in place to maintain the temporal dead zone behavior.

[0030] Duplicate declarations are checked before insertion to avoid semantic errors; if a conflict is detected, promotion is abandoned or the declaration is wrapped in place.

[0031] (5) Function body and statement level wrapping:

[0032] Within function bodies and top-level blocks of statements that can be safely modified, each modifiable statement is wrapped in a single try / catch block to ensure that a single exception does not interrupt the execution of subsequent statements; a strategy of modifying the source code from back to front is adopted while maintaining the integrity of the source code mapping file; special handling strategies are used for specific statements to ensure semantic invariance, including splitting variables with initialization into declaration and initialization sections, and protecting only the initialization section; statements that cannot be safely modified retain their original form; specific statements include variable declarations within function bodies, function termination keywords, and control flow statements;

[0033] (6) Editing conflict and rollback mechanism function:

[0034] Establish conflict detection and debugging switch outputs during instrumentation; including if a file or node cannot be safely rewritten or fails to be parsed, roll back to not rewriting the file and log it to prevent the chain from being interrupted.

[0035] Furthermore, the runtime subsystem includes:

[0036] (1) High-end packaging:

[0037] It provides a unified wrapper function at runtime for wrapping event callbacks, timer callbacks, and third-party callbacks; the higher-order wrapper maintains the semantic transparency of the current function context, parameters, and return values, and captures and reports rejections in the Promise chain; the wrapper logic is parameterized and can inject custom error reporting handlers.

[0038] (2) Framework-level integration:

[0039] Provides Vue plugins and directives to automatically wrap handlers at template event bindings, and uniformly registers framework-level error handlers and component-level captures at the application entry point to collect context and support local degradation;

[0040] (3) Optional application programming interface patching mechanism:

[0041] When needed, a configurable runtime patching mechanism can be used to wrap the event target object, asynchronous object, and network request interface to cover dynamically generated callback scenarios at runtime.

[0042] (4) Reporting client and data processing mechanism: The reported events adopt standardized fields, and the client implements buffering, sampling, deduplication, PII desensitization and offline retry mechanism.

[0043] Furthermore, the strategic self-healing engine includes:

[0044] (1) Strategy Model and Distribution Mechanism:

[0045] The strategy is represented by structured entries, which include matching conditions, action type and parameters, sampling rate, cooldown time and priority; the strategy can be centrally managed and distributed on the server side, or cached on the client side to ensure offline self-healing capability;

[0046] (2) Feature extraction and generation of error fingerprints:

[0047] Feature extraction is performed on abnormal events, and error fingerprints are generated as the primary key for aggregation and policy matching, which reduces the false alarm rate and supports efficient aggregation.

[0048] (3) Decision-making logic and action issuance:

[0049] The decision-making process includes: event reception → feature extraction → strategy matching → generating action execution plans → issuing actions locally or remotely; low-impact actions that can be quickly rolled back are prioritized, while high-impact actions have stricter audit and rollback protection.

[0050] (4) Action executor and rollback strategy:

[0051] The action executor on the client side is responsible for the safe execution and recording of actions such as retry, partial degradation, isolation, function switch switching, and controlled hot patching. It sets an observation window and rollback mechanism for each high-risk action, automatically decides whether to rollback or upgrade based on the evaluation indicators, and sends the evaluation data back to the policy server to complete closed-loop optimization.

[0052] All policy deployments employ digital signatures and auditing mechanisms, supporting canary releases and one-click rollbacks to ensure operational security and controllability.

[0053] This invention also provides a front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite, the method comprising:

[0054] S1. Construction phase pile driving:

[0055] When a developer executes vite build or vite dev, the system calls the Acorn parser to parse the script settings syntax and standard script syntax of each .vue file into an abstract syntax tree (AST).

[0056] After parsing, try / catch wrappers are automatically added to the top-level statements, and local try / catch blocks are inserted into every statement in the function declaration and function body; higher-order wrapper functions are automatically injected into the event callbacks and asynchronous tasks generated by template compilation to ensure that event callbacks and Promise chain exceptions are uniformly entered into the reporting channel.

[0057] After instrumentation is complete, use a string mapping processing library to generate the modified source code and source code mapping file, keeping the debug line numbers unchanged;

[0058] S2. Front-end runtime monitoring:

[0059] After the application starts, the front-end runtime monitoring module is initialized; the system captures global errors and unhandled exception chains through window error event handling functions and uncaught Promise chain rejection events, and captures Vue3 component rendering and lifecycle exceptions through the Vue3 framework's error handling callback interface;

[0060] For code blocks that have been instrumented during the build phase, any error inside a statement or function will be caught by the local try / catch block and reported uniformly by calling the system's global error reporting function.

[0061] S3. Anomaly Reporting and Policy Distribution:

[0062] Abnormal data is transmitted to the backend strategy engine in real time via an encrypted REST interface; the backend strategy engine combines the historical anomaly database, rule engine and machine learning model to generate targeted remediation strategies, including immediate retry, dynamic loading of security modules, and instructing the frontend to perform component-level hot updates.

[0063] S4. Self-healing execution:

[0064] The strategy will execute automatic retries, hot patching, feature degradation, or safety rollback.

[0065] Furthermore, the automatic retry, hot patching, function degradation, or safety rollback are as follows:

[0066] The automatic retry: re-executes the affected initialization function or data request within a safe and controllable number of attempts;

[0067] The hot patch: dynamically loads the repaired component code and replaces the running instance;

[0068] The function degradation refers to disabling some non-core functions and displaying a simplified page after multiple failures to ensure core interactions.

[0069] The safe rollback: when a patch cannot be recovered, revert to the most recent successful stable version or a default safe view.

[0070] The present invention also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the module of the front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite.

[0071] The present invention also provides a non-transitory computer-readable storage medium storing a computer program thereon, wherein the computer program, when executed by a processor, implements the front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite.

[0072] The present invention also provides a computer program product, including a computer program that, when executed by a processor, implements the front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite.

[0073] The interface, configuration, and maintenance considerations of this invention include:

[0074] 1. Plugin configuration items (example);

[0075] 1) Include / Exclude List: Used to define the scope of files or modules that participate in or exclude instrumentation.

[0076] 2) Comment switch: Used to control whether debugging or identifying comments are retained in the code after instrumentation;

[0077] 3) Hoisting options (HoistVars): Used to determine during construction whether top-level variables should undergo safe hoisting and in-order initialization;

[0078] 4) Only process <script setup>选项(onlyScriptSetup):用于限定插桩范围仅针对Vue3单文件组件中的<script setup>结构;

[0079] 5)错误上报处理器参数(reporter):用于指定错误捕获后调用的统一上报接口或回调函数;

[0080] 6)调试模式开关(debug):用于启用插桩与运行期的详细日志输出;

[0081] 7)API修补机制配置(patchAPIs):用于定义运行期需注入代理或钩子的关键浏览器接口。

[0082] 系统支持按文件或模块分组灰度控制,并可依据不同运行环境(开发环境dev、预发布环境preprod、生产环境prod)进行差异化配置。

[0083] 2.安全、隐私与合规;

[0084] 上报前应对可能含有PII的字段做脱敏或掩码处理;热补丁使用签名与白名单机制以防止任意代码注入;动作执行与策略变更保留完整审计记录。

[0085] 3.性能控制策略;

[0086] 通过采样(sample_rate)、跳过热路径(skipHotPaths)、只在script setup插桩(onlyScriptSetup)等手段控制插桩 / 运行期包装带来的运行成本;上报采用批量、去重与节流机制以降低网络与后端负载。

[0087] 本发明替代实施方案与工程变体包括:

[0088] 1.仅运行期包装方案:放弃构建期插桩,仅在运行期对API / 回调做包装(优点:无构建链改造;缺点:无法实现语句级保障)。

[0089] 2.构建期仅在非生产环境启用逐语句插桩,生产环境采用轻量保护(优点:降低生产风险)。

[0090] 3.决策完全服务器化:客户端仅上报,服务器端统一决策并通过下发动作实现修复(优点:策略统一;缺点:存在延迟且离线不可用)。

[0091] 4.第三方脚本隔离优先:对第三方或不可信代码在独立进程执行容器(iframe / worker)中执行以隔离风险(优点:强隔离;缺点:通信复杂、迁移成本高)。

[0092] 上述模块亦可通过浏览器原生并行执行模块WebAssembly或Service Worker的隔离执行方式实现,进一步增强跨平台兼容性。

[0093] 本发明的可实施性声明与补充说明如下:

[0094] 本发明所述技术方案基于现有公开技术与工具(如@vue / compiler-sfc、@babel / parser、acorn、MagicString、Vite插件机制)可以由本领域技术人员在不进行创造性劳动的前提下实现。为便于说明书编写与审查,代码实现细节、伪代码或示例可作为附录或实施例单独列出;在主文中保持对技术措施、步骤、参数、接口与可替代方案的完整描述,以突出本发明的创新点与工程可行性。

[0095] 本发明的有益效果是:

[0096] 本发明通过"构建期逐语句 / 语块插桩+运行期多层包装+策略化自愈”的完整方案,本发明在前端应用的异常检测、定位与自动修复方面带来显著的技术与经济价值。

[0097] 首先,本发明能够显著提高异常的捕获率;构建期的语句级插桩与运行期的高阶包装函数、安全代理以及API补丁结合使用,可以覆盖顶层初始化、函数体内部、事件回调、Promise链和动态导入等场景,从而在异常发生的最早位置进行拦截与记录;与仅依赖被动的全局或框架级错误处理相比,本发明新方案的错误捕获能力得到显著增强,其覆盖范围更为全面;这是由编译期逐语句插桩与运行期统一包装的双重机制直接带来的,属于本发明特有的技术效果;注入故障用例进行验证时,异常捕获和上报的完整性明显增强;

[0098] 其次,本发明降低了白屏和功能中断的概率;由于每条语句和关键模块都进行了try / catch包装,即使单条语句出错,也不会导致整个组件或页面崩溃;同时策略化自愈机制可以在检测到频繁错误后自动降级或隔离风险模块;实际灰度验证表明,本发明新方案能有效降低关键页面的白屏率与核心功能中断率,从而显著提升应用的整体可用性与用户体验;

[0099] 再次,本发明有效缩短了平均故障修复时间;自动化上报包含完整的执行上下文、源映射信息和用户操作轨迹,配合自动重试、模块降级或热修补策略,可辅助大幅减少人工排查和修复时间;在实际试点环境的验证中,本发明新方案能够显著缩短故障的平均定位与恢复时间,从而有效缓解运维压力;

[0100] 此外,本发明的策略化自愈功能可以在无需人工干预的情况下恢复部分故障;对于可重试的初始化失败、短时接口异常等常见场景,本发明新方案可实现有效的自动化处理,显著降低了人工介入的频率与必要性;该自愈机制还具备安全控制和审计记录功能,所有策略下发与补丁应用均可追溯和回滚,保证生产环境的安全性和合规性;

[0101] 在工程实现方面,本发明通过保守的语法分析和插桩策略,避免了重复声明、临时性变量作用域等语义问题;同时提供注释开关、白名单、采样率和跳过热路径等控制手段,将性能开销控制在可接受范围;实际基准测试显示,本发明新方案在运行时产生的额外性能开销极低,对CPU占用与响应时延的影响小,网络传输方面也通过批量合并与流量节流机制进行了充分优化;

[0102] 综合来看,本发明在技术上实现了高覆盖率的前端异常检测、低中断率的容错运行、自动化的故障自愈和辅助可量化的运维成本下降;在经济与社会层面提升了用户体验和关键业务指标,降低了长期维护与人力成本,具备突出的实用价值与创新意义。附图说明

[0103] 图1是本发明的整体架构图;

[0104] 图2是本发明的构建期插桩流程图;

[0105] 图3是本发明的用户使用流程流转图;

[0106] 图4是本发明构建期插桩子系统部分代码示例图一;具体的,为一段示例js代码,正常运行后在行6抛出异常,程序终止;

[0107] 图5是本发明构建期插桩子系统部分代码示例图二;具体的,图5是图4经自动插桩后的js代码,该段代码对顶层语句以及函数体进行了try / catch包装,实现了异常自动捕获处理,从而保证了程序不会因不致命的异常而导致整个崩溃。具体实施方式

[0108] 实施例1:为解决现有技术中前端运行时异常检测覆盖不足、构建期插桩语义风险及缺乏自动自愈闭环等问题,本发明提出一种"构建期插桩(Build-timeinstrumentation)+运行期多层防护(Runtime multi-layer protection)+策略化自愈引擎(Policy-driven self-healing)”的一体化技术方案。该方案在构建阶段对源码进行可控性的逐语句或语句块插桩与顶层变量安全处理,在运行期通过高阶包装器、框架指令与可选API补丁做兜底覆盖,并由本地 / 远端策略库驱动决策与动作执行,形成从"检测—决策—执行—反馈”的闭环自愈体系。与现有仅提供全局监听或框架错误边界的方案不同,本发明的创新点在于构建期自动逐语句插桩与策略化自愈回滚的结合,实现了语句级异常不中断执行,这是现有文献和产品没有的。

[0109] 本发明实施例1面向现代Web单页应用(SPA),能够在不改变框架核心代码的前提下,实现全生命周期的异常防护与自愈。下面结合附图与实施例对本发明作进一步说明,但并不因此限制本发明的保护范围。

[0110] 本发明便于说明书阅读,部分的术语说明包括:

[0111] SPA:Single Page Application(单页应用);

[0112] SFC:Single File Component(Vue单文件组件,.vue);

[0113] HOF:Higher-Order Function(高阶函数);

[0114] fingerprint:错误指纹(对错误堆栈或关键帧计算的哈希,用于聚合与策略匹配);

[0115] <script setup>:脚本设置语法;

[0116] <script>:标准脚本语法;

[0117] Const:常量声明;

[0118] TDZ(Temporal Dead Zone):暂时性死区;

[0119] Hoist:提升;

[0120] SourceMap:源码映射文件;

[0121] 函数结束关键字:return;

[0122] debug:调试开关;

[0123] try / catch:JavaScript中用于处理异常的标准语句结构;

[0124] Promise链:是JS中处理异步操作的对象;

[0125] safeHandler(fn):高阶包装函数;

[0126] window.onerror:窗口错误事件处理函数;

[0127] unhandledrejection:未捕获Promise链拒绝事件;

[0128] app.config.errorHandler:错误处理回调接口;

[0129] window.__reportError:系统全局错误上报函数;

[0130] MagicString:字符串映射处理库;

[0131] vite build:表示构建生产版本;

[0132] vite dev:表示启动开发服务器;

[0133] 如图1-图4所示,基于Vue3与Vite的前端智能异常防护自愈装置,所述装置包括:

[0134] 构建期插桩子系统(Vite插件模块):

[0135] 位置:构建工具链(Vite)内;

[0136] 功能:用于解析并改写源文件(Vue SFC的<script setup> / <script>、.js、.ts),通过抽象语法树(AST)分析,在可控范围内对顶层与函数体语句进行逐条或逐块保护插桩,处理顶层变量安全的变量提升(Hoist)与按序初始化,输出插桩后生成的代码包(Instrumented Bundle)及源码映射文件,用于保证运行期调试与错误定位的可追溯性;

[0137] 运行期子系统(客户端模块):

[0138] 位置:浏览器端运行时;

[0139] 功能:用于提供高阶包装器safe-wrapper、Vue插件 / 指令(例如模板事件自动包装)、错误上报客户端(Error Ingest Client)、本地策略缓存与轻量决策执行器;能按需启用对关键浏览器应用编程接口(API)的运行期修补(Patch)机制,通过函数代理或钩子注入方式扩展异常捕获范围,从而增强系统对异步任务、事件回调及网络请求的覆盖能力;

[0140] 策略化自愈引擎(Server / Local Policy):

[0141] 位置:远端策略服务器配合客户端本地缓存;

[0142] 功能:用于策略管理、匹配与下发(包括sample_rate、cooldown、priority设置),提供可审计的动作下发与回滚机制,并基于回传的评估数据优化策略;策略指令采用基于ECDSA的数字签名,客户端在执行前进行公钥验证,确保策略不可被篡改;

[0143] 动作执行器与反馈评估模块(Action Executor&Feedback Evaluator):

[0144] 位置:客户端(执行可回退动作)与服务器(评估与策略调整);

[0145] 功能:用于执行重试、局部降级、隔离、功能开关机制(Feature Flag)切换、受控热补丁动作、监测动作效果并将评估结果回传以完成闭环。

[0146] 进一步地,所述构建期插桩子系统包括实现如下功能:

[0147] (1)、触发与范围控制:

[0148] 触发条件为:基于文件匹配规则(include / exclude)并且支持显式注释开关(例如: / / @wrap-trycatch enable)用于实现灰度部署与回退控制;配置项包含变量提升选项(HoistVars)、仅处理选项(onlyScriptSetup)、报告器(reporter)、调试开关;

[0149] (2)、SFC与脚本定位:

[0150] 利用Vue SFC解析器提取<script setup> / <script>内容与源码偏移(offset),在原.vue文本中精确替换;使用解析器(例如,@babel / parser或acorn)解析脚本为抽象语法树AST,开启位置与范围信息(ranges / locations),用于支持精准改写与源码映射文件生成;

[0151] (3)、对每个语句节点基于语义安全策略进行安全性分析:

[0152] 在语法树遍历过程中,构建期插桩子系统基于语义安全策略对每个语句节点进行安全性分析;所述语义安全策略,是指在插桩前通过静态语义判断,确定目标语句的执行上下文是否允许被改写或包裹,从而避免插桩后引入语义歧义或副作用,具体而言,当检测到以下语句节点时,构建期插桩子系统将按照保守策略跳过自动插桩:

[0153] 声明目标非标识符的变量声明语句;

[0154] 包含eval(动态求值)、with(动态作用域)或generator(生成器函数)语句;

[0155] 导入、导出及类声明语句;

[0156] 对被跳过的节点,记录其语法位置信息,用于在人工审查阶段进行针对性验证;通过该策略,可确保插桩后的代码在运行期仍保持与原始语义一致,避免因改写导致潜在逻辑错误;

[0157] (4)、顶层变量安全提升与按序初始化:

[0158] 在满足安全条件(声明目标为简单标识符、无重复声明风险)下,收集可变量提升的顶层变量名并在脚本头部前置声明(例如,let脚本头部a,b;),同时在原声明位置按照源代码原有顺序插入每个变量的初始化语句的保护版本;

[0159] 对常量声明或可能触发暂时性死区的情形,不进行拆分变量提升,而采用在原位整体包裹初始化语句的方式以保持暂时性死区行为;

[0160] 在插入前检测重复声明用于避免语义错误;若检测到冲突则放弃提升或改为原位包裹;

[0161] (5)、函数体与语句级逐条包装(倒序替换思想):

[0162] 在函数体内部及顶层可安全改写的语句块中,对每条可改写语句进行单条try / catch包裹,使单条异常不会中断后续语句的执行;为避免编辑冲突,采用从后向前(倒序)修改源码的策略并保持源码映射文件的完整性;对特定语句采用专门处理策略用于保证语义不变,包括将带初始化的变量拆分为声明与初始化两段,并只对初始化段进行保护;对无法安全改写的语句保留原始形式;特定语句包括函数体内的变量声明、函数结束关键字、控制流语句;

[0163] (6)、编辑冲突与回退机制功能:

[0164] 在插桩过程中建立冲突检测与调试开关输出;包括在某个文件或节点上出现无法安全改写或解析失败,回退到不改写该文件并记录日志,以免构建链中断。

[0165] 进一步地,所述运行期子系统包括:

[0166] (1)、高阶包装器(safe-wrapper):

[0167] 在运行期提供统一的包装函数用于包装事件回调、定时器回调、第三方回调;高阶包装器保持当前函数上下文、参数与返回值语义透明,并对Promise链的拒绝进行捕获与上报;包装逻辑参数化,能注入自定义错误上报处理器(reporter);

[0168] (2)、框架级集成(Vue插件 / 指令):

[0169] 提供Vue插件与指令以在模板事件绑定处自动包装处理器,并在应用入口统一注册框架级错误处理器(app.config.errorHandler)与组件级捕获(onErrorCaptured),用于收集上下文并支持本地降级;

[0170] (3)、可选的应用编程接口(API)修补机制(Patch):

[0171] 在需要时,通过可配置的运行期修补(Patch)机制,对事件目标对象(EventTarget)、异步对象及网络请求接口(XHR / fetch)进行包装,用于覆盖运行时动态产生的回调场景。该项为高侵入选项,需在配置中可控打开并限制灰度范围;

[0172] (4)、上报客户端(Error Ingest)与数据处理机制:上报事件采用标准化字段(例如id、fingerprint、type、message、stack、componentPath、time、breadcrumbs、stateSnapshot、env、source等),并在客户端实现缓冲、采样、去重、PII脱敏与离线重试机制。

[0173] 进一步地,所述策略化自愈引擎包括:

[0174] (1)、策略模型与下发机制:

[0175] 策略以结构化条目表示,包含匹配条件、动作类型与参数、采样率、冷却时间与优先级;策略既能在服务器端集中管理并下发,也能缓存于客户端用于保障离线自愈能力;

[0176] (2)、特征抽取与生成错误指纹(Fingerprint——根据异常堆栈生成的唯一标识):

[0177] 对异常事件进行特征抽取(例如堆栈摘要、组件路径、错误类型、上下文快照等),并生成错误指纹作为聚合与策略匹配的主键,用于降低误报率并支持高效聚合;

[0178] (3)、决策逻辑与动作下发:

[0179] 决策流程包括:事件接收→特征抽取→策略匹配→生成动作执行计划(ActionPlan)→本地或远端动作下发;优先执行低影响、可快速回滚的动作(如retry、局部降级),高影响动作(如全量feature-flag切换、热补丁)具备更严格的审计与回滚保障;

[0180] (4)、动作执行器与回滚策略:

[0181] 动作执行器在客户端承担重试、局部降级、隔离、功能开关切换(Flag Toggle)、受控热补丁等动作的安全执行并记录审计;对每个高风险动作设定观察窗口与回滚机制,根据评估指标自动决定是否回滚或升级处理,并将评估数据回传策略服务器用于完成闭环优化;

[0182] 所有策略下发均采用数字签名与审计机制,支持灰度发布与一键回滚,用于确保运行期安全可控。

[0183] 本发明还提供基于Vue3与Vite的前端智能异常防护自愈方法,所述方法包括:

[0184] S1.构建期插桩:

[0185] 当开发者执行vite build或vite dev时,系统调用Acorn解析器,将每个.vue文件的脚本设置语法与标准脚本语法部分解析为抽象语法树AST;

[0186] 解析完成后,自动为顶层语句添加try / catch包装,并对函数声明及函数体内的每一条语句插入局部try / catch;对模板编译生成的事件回调和异步任务,自动注入safeHandler(fn),确保事件回调和Promise链异常统一进入报告通道;

[0187] 插桩完成后,利用MagicString生成修改后的源码与SourceMap,保持调试行号不变;在默认配置下,采样率为100%,可通过vite.config.js调整至10%–100%。以下为Vite插件配置示例:wrapTryCatch({include:[ / \\.vue$ / ],HoistVars:true,reporter:'window.__reportError'});

[0188] S2.前端运行时监控:

[0189] 在应用启动后,前端运行时监控模块初始化;系统通过window.onerror与unhandledrejection捕获全局错误与未处理异常链,通过Vue3框架的app.config.errorHandler捕获Vue3组件渲染及生命周期异常;

[0190] 对于构建期已插桩的代码块,任意语句或函数内部错误均会被局部try / catch捕获并调用window.__reportError统一上报;

[0191] S3.异常上报与策略下发:

[0192] 异常数据通过加密的REST接口实时传输到后端策略引擎;后端策略引擎结合历史异常库、规则引擎与机器学习模型,生成针对性的修复策略,包括立即重试、动态加载安全模块、指示前端执行组件级热更新;

[0193] S4.自愈执行:

[0194] 根据策略执行自动重试、热修补、功能降级或安全回退。

[0195] 进一步地,所述自动重试、热修补、功能降级或安全回退为:

[0196] 所述自动重试:在安全可控的次数内重新执行受影响的初始化函数或数据请求;

[0197] 所述热修补:动态加载修复后的组件代码并替换运行实例;

[0198] 所述功能降级:多次失败后禁用部分非核心功能并展示简化页面用于保证核心交互;

[0199] 所述安全回退:在修补无法恢复时回退到最近一次成功的稳定版本或预置的安全视图,从而避免全局崩溃。

[0200] 本发明还提供 一种电子设备,包括存储器、处理器及存储在所述存储器上并可在所述处理器上运行的计算机程序,所述处理器执行所述程序时实现所述基于Vue3与Vite的前端智能异常防护自愈方法的模块。

[0201] 本发明还提供 一种非暂态计算机可读存储介质,其上存储有计算机程序,所述计算机程序被处理器执行时实现所述基于Vue3与Vite的前端智能异常防护自愈方法。

[0202] 本发明还提供一种计算机程序产品,包括计算机程序,所述计算机程序被处理器执行时实现所述基于Vue3与Vite的前端智能异常防护自愈方法。

[0203] 对于本发明的可选方案与扩展:

[0204] 在不脱离本发明核心思路的前提下,可根据实际项目选择其他前端框架(如React、Svelte)或构建工具(如Webpack、Rollup)实现相同的插桩与自愈逻辑;异常上报与策略引擎亦可替换为第三方服务(如Sentry、Elastic APM),这些均属于本发明的等效变形与扩展。

[0205] 通过上述S1至S4的完整流程,本发明实现了"构建期插桩—运行期监控—策略化自愈—安全回退”的全链路技术方案,可在前端应用发生未知错误时实现实时检测、局部修复与自动恢复,显著提升系统稳定性和用户体验。具体而言,系统在构建阶段利用Vite插件对子代码进行语句级try / catch插桩与顶层变量安全提升,保证在运行期即便出现异常也能被精准捕获并上报(参见附图4-图5:构建期插桩子系统实际效果图)。在实际应用中,本发明能够自愈的异常类型包括但不限于:

[0206] 运行时脚本异常。例如业务逻辑函数中的ReferenceError、TypeError、SyntaxError 等。插桩后的语句级捕获可在错误发生时不中断后续代码执行。

[0207] Promise链 / 异步异常。未捕获Promise链拒绝事件、网络请求失败、异步任务链中的未捕获异常。通过全局Promise包装器和安全包装器(Safe-Wrapper)实现统一处理与重试策略。

[0208] 资源加载异常。图片、脚本、样式文件加载失败(window.onerror资源错误)。系统可自动降级UI组件或切换备用资源。

[0209] 第三方依赖异常。第三方SDK、广告脚本或微前端子应用运行时崩溃。可即时隔离问题模块并回退到安全版本。

[0210] 状态不一致或内存泄漏导致的异常。例如关键变量被意外清空、组件反复渲染导致的栈溢出。策略引擎可下发热补丁或触发轻量级页面重置以恢复。

[0211] 通过这些能力,本发明实现了自动检测—快速响应—局部修复—闭环反馈的完整自愈流程,既保证了终端用户的交互连续性,也为开发运维人员提供了可观测、可回滚的安全保障,大幅降低了前端系统因未知错误而导致的宕机和用户流失风险。

[0212] 本发明针对前端应用在运行过程中可能出现的语法错误、运行时异常、组件渲染失败以及事件处理错误等问题,提供一套集实时监测、自动捕获、智能修复与可视化回溯于一体的技术方案,属于Web前端运行监控与智能容错自愈技术领域。此外,本方案的核心插桩与自愈机制并不限于Vue3 / Vite,可平滑迁移至 React、Svelte等其他现代前端框架和构建工具。该方案尤其适用于电商、在线教育及大型SaaS平台等高可用Web应用,对保障业务连续性具有重要意义。

[0213] 本发明解决了现有技术中运行时异常检测覆盖不足、定位与修复滞后、对动态 / 第三方代码覆盖率低以及构建期插桩易引入语义风险等技术问题。本发明实现了以下具体任务:

[0214] 1、统一的异常检测与拦截。在应用构建阶段自动完成代码插桩,对顶层语句、函数体及关键逻辑单元进行细粒度try / catch包装,实现从语句级到模块级的实时异常捕获,而无需开发者手工维护。

[0215] 2、运行时多层次监控。结合全局监听、框架级错误边界与自动插桩,实现对同步代码、异步回调、动态模块及事件处理的全覆盖监控,提升异常捕捉率和定位精度。

[0216] 3、异常自愈与动态恢复。通过高阶包装函数、状态回溯与降级渲染策略,对检测到的运行时异常自动执行隔离、重试或动态补丁加载,确保在发生严重错误时应用核心功能可持续运行。

[0217] 4、自动化部署与低侵入集成。依托Vite插件机制,方案可直接嵌入现有Vue3项目的构建流程,减少人工配置和重复性工作,保证升级迭代的可维护性与稳定性。

[0218] 本发明能够在前端生产环境实现"检测—隔离—修复—回溯”的一体化闭环,显著提高Web应用的稳定性和自恢复能力,为大规模前端工程提供可靠的异常防护与自愈解决方案。与传统仅依赖开发者手动增加容错逻辑的方案相比,本发明通过编译期语法树分析与自动插桩,实现了前端语句级的全自动化保护,这是现有技术未公开也未预期到的改进。本发明将前端异常捕获率提高了,关键页面白屏率下降了,显著优于现有Sentry等仅上报不自愈的技术。

[0219] 上面结合附图对本发明的具体实施方式作了详细说明,但是本发明并不限于上述实施方式,在本领域普通技术人员所具备的知识范围内,还可以在不脱离本发明宗旨的前提下作出各种变化。< / script>

Claims

1. A front-end intelligent anomaly protection and self-healing device based on Vue3 and Vite, characterized in that: The device includes: The build-time instrumentation subsystem is located within the build toolchain. It is used to parse and rewrite source files, analyze abstract syntax trees, and perform line-by-line or block-by-block protection instrumentation on top-level and function body statements within a controllable range. It handles safe variable hoisting and sequential initialization of top-level variables, and outputs the generated code package and source code mapping file after instrumentation to ensure the traceability of runtime debugging and error location. Runtime subsystem: Provides higher-order wrappers, Vue plugins / directives, error reporting clients, local strategy caching, and lightweight decision executors; enables runtime patching mechanisms for critical browser application programming interfaces as needed, and extends the scope of exception handling through function proxies or hook injection. High-end packaging: It provides a unified wrapper function at runtime for wrapping event callbacks, timer callbacks, and third-party callbacks; the higher-order wrapper maintains the semantic transparency of the current function context, parameters, and return values, and captures and reports rejections in the Promise chain; the wrapper logic is parameterized and can inject custom error reporting handlers. Strategic self-healing engine: used for strategy management, matching and distribution, decision logic and action distribution. The decision-making process includes: executing actions in the order of event reception, feature extraction, policy matching, generating action execution plans, and issuing local or remote actions; prioritizing low-impact actions that can be quickly rolled back, while providing stricter audit and rollback guarantees for high-impact actions; providing auditable action issuance and rollback mechanisms, and optimizing policies based on the returned evaluation data; policy instructions use ECDSA-based digital signatures, and the client verifies the public key before execution. The strategic self-healing engine includes an action executor and a feedback evaluation module: used to perform retries, local degradation, isolation, function switch mechanism switching, controlled hot patching actions, monitor the effects of actions, and send back the evaluation results to complete the closed loop.

2. The front-end intelligent anomaly protection and self-healing device based on Vue3 and Vite according to claim 1, characterized in that: The construction phase piling subsystem includes the following functions: (1) Triggering and range control: The triggering conditions are: based on file matching rules and supporting explicit comment switches for canary deployment and rollback control; configuration items include variable promotion options, processing-only options, reporter, and debug switch; (2) SFC and script positioning: The Vue SFC parser is used to extract script setting syntax, standard script syntax content, and source code offsets, which are then precisely replaced in the original .vue text. The parser is used to parse the script into an abstract syntax tree (AST), with position and range information enabled to support precise rewriting and the generation of source code mapping files. (3) Perform security analysis on each statement node based on semantic security policy: During syntax tree traversal, the build-time instrumentation subsystem performs security analysis on each statement node based on a semantic safety strategy. This semantic safety strategy refers to determining, before instrumentation, whether the execution context of the target statement can be rewritten or wrapped through static semantic judgment. Specifically, when the following statement nodes are detected, the build-time instrumentation subsystem will skip automatic instrumentation according to a conservative strategy: A variable declaration statement that declares a target that is not an identifier; Statements that include dynamic evaluation, dynamic scoping, or generator functions; Import, export, and class declaration statements; For skipped nodes, their syntax position information is recorded for targeted verification during the manual review stage. This strategy ensures that the instrumented code remains consistent with the original semantics at runtime, avoiding potential logical errors caused by rewriting. (4) Top-level variable hoisting and sequential initialization: Under the condition of meeting safety requirements, collect the top-level variable names that can be promoted and declare them at the beginning of the script. At the same time, insert the protected version of the initialization statement of each variable in the original order of the source code at the original declaration position. For constant declarations or cases that trigger the temporal dead zone, variable hoisting is not performed; instead, the initialization statement is wrapped in place to maintain the temporal dead zone behavior. Duplicate declarations are checked before insertion to avoid semantic errors; if a conflict is detected, promotion is abandoned or the declaration is wrapped in place. (5) Function body and statement level wrapping: Within the function body and in the top-level safe-to-modify statement block, each modifiable statement is wrapped in a single try / catch block to ensure that a single exception will not interrupt the execution of subsequent statements. The strategy of modifying the source code from back to front is adopted while maintaining the integrity of the source code mapping file; a processing strategy is adopted for variable declarations, function termination keywords, and control flow statements in the function body to ensure semantic invariance, including splitting variables with initialization into declaration and initialization sections, and protecting only the initialization section; the original form of statements that cannot be safely rewritten is retained. (6) Editing conflict and rollback mechanism function: Establish conflict detection and debugging switch outputs during the pile driving process; This includes preventing unsafe rewriting or parsing failures on a file or node, rolling back to not rewriting the file, and logging the process to avoid chain disruptions.

3. The front-end intelligent anomaly protection and self-healing device based on Vue3 and Vite according to claim 1, characterized in that: The runtime subsystem also includes: (1) Framework-level integration: Provides Vue plugins and directives to automatically wrap handlers at template event bindings, and uniformly registers framework-level error handlers and component-level captures at the application entry point to collect context and support local degradation; (2) Optional application programming interface patching mechanism: When needed, a configurable runtime patching mechanism can be used to wrap the event target object, asynchronous object, and network request interface to cover dynamically generated callback scenarios at runtime. (3) Reporting client and data processing mechanism: The reported events adopt standardized fields, and the client implements buffering, sampling, deduplication, PII desensitization and offline retry mechanism.

4. The front-end intelligent anomaly protection and self-healing device based on Vue3 and Vite according to claim 1, characterized in that: The strategic self-healing engine includes: (1) Strategy Model and Distribution Mechanism: The strategy is represented by structured entries, which include matching conditions, action type and parameters, sampling rate, cooldown time and priority; the strategy can be centrally managed and distributed on the server side, or cached on the client side to ensure offline self-healing capability; (2) Feature extraction and generation of error fingerprints: Feature extraction is performed on abnormal events, and error fingerprints are generated as the primary key for aggregation and policy matching, which reduces the false alarm rate and supports efficient aggregation. (3) Action executor and rollback strategy: The action executor on the client side is responsible for the safe execution and recording of actions such as retry, partial degradation, isolation, function switch switching, and controlled hot patching. It sets an observation window and rollback mechanism for each high-risk action, automatically decides whether to rollback or upgrade based on the evaluation indicators, and sends the evaluation data back to the policy server to complete closed-loop optimization. All policy deployments employ digital signatures and auditing mechanisms, supporting canary releases and one-click rollbacks to ensure operational security and controllability.

5. A front-end intelligent exception protection and self-healing method based on Vue3 and Vite, characterized in that, The method includes: S1. Construction phase pile driving: When a developer executes vite build or vite dev, the system calls the Acorn parser to parse the script settings syntax and standard script syntax of each .vue file into an abstract syntax tree (AST). After parsing, try / catch wrappers are automatically added to the top-level statements, and local try / catch blocks are inserted into every statement in the function declaration and function body; higher-order wrapper functions are automatically injected into the event callbacks and asynchronous tasks generated by template compilation to ensure that event callbacks and Promise chain exceptions are uniformly entered into the reporting channel. After instrumentation is complete, use a string mapping processing library to generate the modified source code and source code mapping file, keeping the debug line numbers unchanged; S2. Front-end runtime monitoring: After the application starts, the front-end runtime monitoring module is initialized; the system captures global errors and unhandled exception chains through window error event handling functions and uncaught Promise chain rejection events, and captures Vue3 component rendering and lifecycle exceptions through the Vue3 framework's error handling callback interface; For code blocks that have been instrumented during the build phase, any error inside a statement or function will be caught by the local try / catch block and reported uniformly by calling the system's global error reporting function. S3. Anomaly Reporting and Policy Distribution: Abnormal data is transmitted to the backend strategy engine in real time via an encrypted REST interface; the backend strategy engine combines the historical anomaly database, rule engine and machine learning model to generate targeted remediation strategies, including immediate retry, dynamic loading of security modules, and instructing the frontend to perform component-level hot updates. S4. Self-healing execution: The strategy will execute automatic retries, hot patching, feature degradation, or safety rollback.

6. The front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite according to claim 5, characterized in that, The automatic retry, hot patching, function degradation, or safety rollback are: The automatic retry: re-executes the affected initialization function or data request within a safe and controllable number of attempts; The hot patch: dynamically loads the repaired component code and replaces the running instance; The function degradation refers to disabling some non-core functions and displaying a simplified page after multiple failures to ensure core interactions. The safe rollback: when a patch cannot be recovered, revert to the most recent successful stable version or a default safe view.

7. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the front-end intelligent exception protection and self-healing method based on Vue3 and Vite as described in any one of claims 5 to 6.

8. A non-transitory computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite as described in any one of claims 5 to 6.

9. A computer program product, comprising a computer program, characterized in that, When the computer program is executed by the processor, it implements the front-end intelligent anomaly protection and self-healing method based on Vue3 and Vite as described in any one of claims 5 to 6.

Citation Information

Patent Citations

  • Application exception processing method and device, and computer readable storage medium

    CN113791809A

  • Method for efficiently collecting front-end abnormal information based on terminal equipment

    CN119961094A