### Install @seed-fe/exception-handler Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Instructions for installing the exception handler library using npm, yarn, or pnpm. ```bash # 使用 npm npm install @seed-fe/exception-handler # 使用 yarn yarn add @seed-fe/exception-handler # 使用 pnpm (推荐) pnpm add @seed-fe/exception-handler ``` -------------------------------- ### Basic Usage: Create Exception Catcher Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Demonstrates how to create an exception catcher with a logger handler, enable standard capture, and console error output. It also shows how to start the catcher and manually capture exceptions with metadata. ```typescript import { createExceptionCatcher } from '@seed-fe/exception-handler'; // 创建异常捕获器 - 现在支持所有参数在一个配置对象中 const catcher = createExceptionCatcher({ handlers: [ { name: 'logger', condition: () => true, handler: async (context) => { console.log('捕获到异常:', context.error.message); } } ], enableStandardCapture: true, // 启用标准异常捕获 enableConsoleError: true // 启用控制台错误输出 }); // 启动标准异常监听 catcher.start(); // 手动捕获异常 catcher.captureException(new Error('自定义错误'), { source: 'user-action', metadata: { userId: '123', page: '/dashboard' } }); ``` -------------------------------- ### Parallel and Serial Exception Processing Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Explains and demonstrates the `mode` property for handlers, allowing them to be executed in parallel or serially. Includes examples for both modes. ```typescript const handlers = [ { name: 'parallel-logger', condition: () => true, handler: async (context) => { console.log('并行处理 1'); }, mode: 'parallel' // 并行执行 }, { name: 'parallel-reporter', condition: () => true, handler: async (context) => { console.log('并行处理 2'); }, mode: 'parallel' // 与上面同时执行 }, { name: 'serial-cleanup', condition: () => true, handler: async (context) => { console.log('串行处理,在并行处理完成后执行'); }, mode: 'serial' // 默认串行 } ]; ``` -------------------------------- ### Conditional Exception Handling Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Illustrates how to configure handlers with specific conditions to process different types of errors. It includes an example for reporting critical errors and logging all errors. ```typescript const handlers = [ { name: 'error-reporter', condition: (context) => context.error.message.includes('critical'), handler: async (context) => { // 只处理关键错误 await reportToService(context.error); } }, { name: 'logger', condition: () => true, handler: async (context) => { // 记录所有错误 console.log(context.error); } } ]; catcher.setHandlers(handlers); ``` -------------------------------- ### Vue Framework Integration Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Provides code examples for integrating the exception handler with Vue 2 and Vue 3 error handling mechanisms. ```typescript // Vue 2 Vue.config.errorHandler = (error, vm, info) => { catcher.captureException(error, { source: 'vue2', metadata: { info, componentName: vm?.$options.name } }); }; // Vue 3 app.config.errorHandler = (error, instance, info) => { catcher.captureException(error, { source: 'vue3', metadata: { info, componentName: instance?.$?.type?.name } }); }; ``` -------------------------------- ### Leading and Trailing Hooks Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Details the usage of leading and trailing hooks for pre-processing and post-processing exception handling. Shows how to set them during creation or dynamically. ```typescript // 方式1:创建时设置钩子 const catcher = createExceptionCatcher({ handlers: [...], leadingHook: { handler: async (context) => { // 在所有处理器执行前运行 return { userId: getCurrentUserId(), timestamp: Date.now() }; }, breakOnError: true // 前置钩子出错时是否中断处理链 }, trailingHook: { handler: async (context, leadingResult) => { // 在所有处理器执行后运行 console.log('处理完成', leadingResult); } } }); // 方式2:动态设置钩子 catcher.setLeadingHook({ handler: async (context) => { return { userId: getCurrentUserId(), timestamp: Date.now() }; }, breakOnError: true }); catcher.setTrailingHook({ handler: async (context, leadingResult) => { console.log('处理完成', leadingResult); } }); ``` -------------------------------- ### Basic Usage: ExceptionCatcher Constructor Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Shows an alternative way to create an exception catcher using the `ExceptionCatcher` constructor, including setting handlers, a leading hook, and enabling standard capture. ```typescript import { ExceptionCatcher } from '@seed-fe/exception-handler'; // 也可以直接使用构造函数,支持相同的配置参数 const catcher = new ExceptionCatcher({ handlers: [ { name: 'logger', condition: () => true, handler: async (context) => { console.log('捕获到异常:', context.error.message); } } ], leadingHook: { handler: async () => ({ userId: getCurrentUserId() }) }, enableStandardCapture: true }); catcher.start(); ``` -------------------------------- ### ExceptionCatcher Constructor Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Demonstrates the direct instantiation of the `ExceptionCatcher` class. This constructor supports the same configuration options as the `createExceptionCatcher` factory function. ```typescript new ExceptionCatcher(options?: ExceptionCatcherOptions) ``` -------------------------------- ### Dynamic Handler Management: Add, Remove, Update Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Demonstrates how to dynamically manage exception handlers, including adding new handlers, removing existing ones, and updating their configurations. ```typescript // 添加处理器 catcher.addHandler({ name: 'new-handler', condition: () => true, handler: async (context) => { console.log('新处理器'); } }); // 移除处理器 catcher.removeHandler('new-handler'); // 更新处理器 catcher.updateHandler('logger', { name: 'logger', condition: () => false, // 禁用 handler: async () => {} }); // 检查处理器是否存在 if (catcher.hasHandler('logger')) { console.log('logger 处理器存在'); } ``` -------------------------------- ### Symbol-Based Handler Management Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Illustrates using Symbols to create unique identifiers for exception handlers, preventing naming conflicts. It covers adding, updating, and removing handlers using these Symbols. ```typescript // 使用 Symbol 避免命名冲突 const LOGGER_SYMBOL = Symbol('logger'); const REPORTER_SYMBOL = Symbol('reporter'); catcher.addHandler({ name: LOGGER_SYMBOL, condition: () => true, handler: async (context) => { console.log('Symbol 处理器'); } }); // 通过 Symbol 访问 catcher.updateHandler(LOGGER_SYMBOL, newHandler); catcher.removeHandler(LOGGER_SYMBOL); ``` -------------------------------- ### ExceptionCatcher Factory Function Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Shows the usage of the `createExceptionCatcher` factory function to instantiate an exception catcher with configuration options. It accepts the same parameters as the constructor. ```typescript createExceptionCatcher(config?: ExceptionCatcherOptions): ExceptionCatcher ``` -------------------------------- ### Fallback Handler Management Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Demonstrates how to set a fallback exception handler, which is invoked when no other handlers process an error. It also shows how to remove the fallback handler. ```typescript // 设置回退处理器,当没有其他处理器处理异常时使用 catcher.setFallbackHandler({ condition: () => true, handler: async (context) => { console.error('未处理的异常:', context.error); } }); // 移除回退处理器 catcher.removeFallbackHandler(); ``` -------------------------------- ### React Framework Integration Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Shows how to integrate the exception handler with React Error Boundaries and the new `onCaughtError` API in React 19+. ```typescript // Error Boundary class ErrorBoundary extends React.Component { componentDidCatch(error, errorInfo) { catcher.captureException(error, { source: 'react-boundary', metadata: { errorInfo } }); } } // 或使用 React 19+ 的新 API const root = createRoot(container, { onCaughtError: (error, errorInfo) => { catcher.captureException(error, { source: 'react-caught', metadata: { errorInfo } }); } }); ``` -------------------------------- ### Core Type Definitions Source: https://github.com/xianghongai/seed-fe-exception-handler/blob/main/README.md Defines the fundamental types used within the exception handling system, including handler names (string or symbol), context for handlers, the structure of an exception handler, and options for leading/trailing hooks and catcher configuration. ```typescript // 处理器名称:支持字符串和 Symbol type HandlerName = string | symbol; // 异常处理上下文 type HandlerContext = { error: Error; // 错误对象 source: string; // 异常来源 processedBy: ProcessRecord[]; // 处理记录 originalEvent?: ErrorEvent | PromiseRejectionEvent; // 原始事件 leadingResult?: LeadingResult; // 前置钩子结果 metadata?: Record; // 自定义元数据 }; // 异常处理器 type ExceptionHandler = { name?: HandlerName; // 处理器名称 condition: (context: HandlerContext) => boolean | Promise; // 处理条件 handler: (context: HandlerContext) => Promise; // 处理函数 acceptProcessed?: boolean; // 是否接收已处理的异常 mode?: 'serial' | 'parallel'; // 执行模式 }; // 前置钩子 type LeadingHook = { handler: (context: HandlerContext) => Promise; breakOnError?: boolean; // 出错时是否中断处理链,默认 false 不中断 }; // 后置钩子 type TrailingHook = { handler: (context: HandlerContext, leadingResult?: LeadingResult) => Promise; }; // 异常捕获器配置选项 type ExceptionCatcherOptions = { enableStandardCapture?: boolean; // 控制是否自动监听全局 `error` 和 `unhandledrejection` 事件,默认 true enableConsoleError?: boolean; // 控制是否输出库内部的错误日志,默认 true handlers?: ExceptionHandler[]; // 初始异常处理器数组 leadingHook?: LeadingHook; // 初始前置钩子 trailingHook?: TrailingHook; // 初始后置钩子 }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.