共享Node模块抛出异常时instanceof判断失效问题
Puppeteer TimeoutError instanceof 校验失败问题(多模块场景)
问题根源
你的猜测完全正确:主模块和共享模块虽安装了同一版本的Puppeteer,但受Node.js模块解析机制影响,两个模块加载的是独立的Puppeteer实例,各自的TimeoutError构造函数指向不同引用,导致instanceof校验返回false。
解决方案
1. 扁平化依赖,共用同一Puppeteer实例
通过调整依赖结构,让两个模块共享同一个Puppeteer包:
- 执行
npm dedupe命令,自动扁平化项目依赖,将重复的Puppeteer包提升到主模块的node_modules目录,共享模块会自动复用主模块的Puppeteer实例。 - 或者将共享模块的Puppeteer配置为
peerDependencies:
修改共享模块的package.json:
共享模块将不再自行安装Puppeteer,而是依赖主模块提供的版本,确保两者使用同一实例。{ // ... 其他配置 "peerDependencies": { "puppeteer": "^20.7.2" } }
2. 通过错误属性判断替代instanceof
如果不想调整依赖结构,可直接检查错误的标识属性:
try { await page.waitForXPath("//") } catch (error) { // 通过name属性判断错误类型 if (error.name === "TimeoutError") { continue; } else { throw error; } }
Puppeteer内置错误类都会保留对应的name属性,该方法不受模块实例差异影响。
3. 从共享模块导出错误类
在共享模块中直接导出Puppeteer的TimeoutError,主模块使用该导出类进行校验:
共享模块main.js修改:
import * as puppeteer from "puppeteer"; export function throwError() { throw new puppeteer.TimeoutError("Timeout from shared"); } // 导出共享模块的TimeoutError export const TimeoutError = puppeteer.TimeoutError;
主模块main.js修改:
import * as shared from "shared"; try { shared.throwError(); } catch (error) { console.log(error instanceof shared.TimeoutError); // 现在返回true }
内容的提问来源于stack exchange,提问作者jr.
相关产品推荐
相关产品推荐

