You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Angular CLI创建组件时出现catch clause变量非Error实例错误

Angular执行ng g c my-component时出现"catch clause variable is not an Error instance"异常的解决方法

问题描述

执行ng g c my-component命令创建Angular组件时,触发如下异常:

An unhandled exception occurred: catch clause variable is not an Error instance
See "path-to-file\angular-errors.log" for further details.

日志文件中的堆栈跟踪信息:

[error] AssertionError [ERR_ASSERTION]: catch clause variable is not an Error instance
at assertIsError (C:\Users\sam\node_modules@angular\cli\src\utilities\error.js:16:26)
at GenerateCommandModule.runSchematic (C:\Users\sam\node_modules@angular\cli\src\command-builder\schematics-command-module.js:311:43)
at async GenerateCommandModule.handler (C:\Users\sam\node_modules@angular\cli\src\command-builder\command-module.js:109:24)

已尝试过以下更新Angular CLI的操作,但问题未解决:

npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm cache verify
npm install -g @angular/cli@latest

项目的package.json内容:

{
  "name": "my-sample-frontend",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.1.0",
    "@angular/common": "^14.1.0",
    "@angular/compiler": "^14.1.0",
    "@angular/core": "^14.1.0",
    "@angular/forms": "^14.1.0",
    "@angular/platform-browser": "^14.1.0",
    "@angular/platform-browser-dynamic": "^14.1.0",
    "@angular/router": "^14.1.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.1.0",
    "@angular/cli": "~14.1.0",
    "@angular/compiler-cli": "^14.1.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.2.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  }
}

解决方案

1. 同步全局与本地Angular CLI版本

当前全局安装的是最新版CLI,但项目本地依赖的是~14.1.0版本,版本不匹配是常见诱因。执行以下命令安装与项目匹配的全局CLI版本:

npm install -g @angular/cli@14.1.0

2. 清理本地依赖并重新安装

删除项目根目录下的node_modules文件夹和package-lock.json文件,彻底清理后重新安装依赖:

# Windows系统
rmdir /s /q node_modules
del package-lock.json

# macOS/Linux系统
rm -rf node_modules package-lock.json

# 重新安装依赖
npm install

3. 检查Node.js版本兼容性

Angular 14要求Node.js版本为14.15.x、16.x或18.x(LTS版本)。运行node -v查看当前版本,若不兼容,升级或降级到对应版本。

4. 重置Angular CLI缓存

执行命令清空CLI的本地缓存,避免缓存异常导致的问题:

ng cache clean --all

5. 使用本地CLI执行命令

直接调用项目本地的CLI工具,规避全局与本地版本冲突:

npx ng g c my-component

内容的提问来源于stack exchange,提问作者Anant Bhatnagar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:48:51