## 常見錯誤
在使用Nestjs開發時,可能遇到不同錯誤。
### `Cannot resolve dependency(無法處理依賴)`錯誤
最常見的錯誤信息可能是Nest無法處理提供者依賴,這個錯誤看上去往往像這樣:
```bash
Nest can't resolve dependencies of the <provider> (?). Please make sure that the argument <unknown_token> at index [<index>] is available in the <module> context.
Potential solutions:
- If <unknown_token> is a provider, is it part of the current <module>?
- If <unknown_token> is exported from a separate @Module, is that module imported within <module>?
@Module({
imports: [ /* the Module containing <unknown_token> */ ]
})
```
這個錯誤最常用的原因,是提供者沒有列在模塊的`provider`數組中。確保提供者在提供者數組中并且遵循以下NestJs提供者實踐。
有一些常規的錯誤。其中一個是把提供者放到了`import`數組里。在這種情況下,錯誤會是提供者的名字在`<module>`應該在的地方。
如果你在開發過程中遇到這些錯誤,看看提到的出錯信息以及其提供者。確保提供者在提供者數組中,模塊可以訪問所有的依賴。有時提供者在"Feature Module"和"Root Module"中重復,這意味著Nest將嘗試實例化提供者兩次。更可能的是,從模塊復制的提供者應該替換為在"Root Module"的`imports`數組中引入。
### `Circular dependency(循環依賴)`錯誤
有時你會發現在應用中無法避免循環依賴。你可能需要做一些工作來幫助Nest解決它,循環依賴錯誤看上去可能像這樣:
```bash
Nest cannot create the <module> instance.
The module at index [<index>] of the <module> "imports" array is undefined.
Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [<index>] is of type "undefined". Check your import statements and the type of the module.
Scope [<module_import_chain>]
# example chain AppModule -> FooModule
```
### 調試依賴錯誤
除了手動驗證您的依賴項是否正確之外,從 Nest 8.1.0 開始,您可以將“NEST\_DEBUG”環境變量設置為解析為真值的字符串,并在 Nest 解析應用程序的所有依賴項時獲取額外的日志信息。

在上圖中,黃色字符串是被注入依賴的宿主類,藍色字符串是注入依賴的名稱,或者它的注入令牌,紫色字符串是依賴所在的模塊搜索。使用它,您通常可以追溯發生了什么以及為什么會出現依賴注入問題的依賴解析。
循環依賴錯誤可能來自提供者間的相互依賴,或者TypeScript文件常量相互依賴,例如從一個模型文件中導出常量而在一個服務中引入他們。在后一種情況下,建議為常量創建一個獨立的文件。在前一種情況下,查看循環依賴指導并保證兩個模塊和提供者都標記有`forwarRef`。
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- Mongo
- 配置
- 驗證
- 緩存
- 序列化
- 版本控制
- 定時任務
- 隊列
- 日志
- Cookies
- 事件
- 壓縮
- 文件上傳
- 流式處理文件
- HTTP模塊
- Session(會話)
- MVC
- 性能(Fastify)
- 服務器端事件發送
- 安全
- 認證(Authentication)
- 授權(Authorization)
- 加密和散列
- Helmet
- CORS(跨域請求)
- CSRF保護
- 限速
- GraphQL
- 快速開始
- 解析器(resolvers)
- 變更(Mutations)
- 訂閱(Subscriptions)
- 標量(Scalars)
- 指令(directives)
- 接口(Interfaces)
- 聯合類型
- 枚舉(Enums)
- 字段中間件
- 映射類型
- 插件
- 復雜性
- 擴展
- CLI插件
- 生成SDL
- 其他功能
- 聯合服務
- 遷移指南
- Websocket
- 網關
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 適配器
- 微服務
- 概述
- Redis
- MQTT
- NATS
- RabbitMQ
- Kafka
- gRPC
- 自定義傳輸器
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 獨立應用
- Cli
- 概述
- 工作空間
- 庫
- 用法
- 腳本
- Openapi
- 介紹
- 類型和參數
- 操作
- 安全
- 映射類型
- 裝飾器
- CLI插件
- 其他特性
- 遷移指南
- 秘籍
- CRUD 生成器
- 熱重載
- MikroORM
- TypeORM
- Mongoose
- 序列化
- 路由模塊
- Swagger
- 健康檢查
- CQRS
- 文檔
- Prisma
- 靜態服務
- Nest Commander
- 問答
- Serverless
- HTTP 適配器
- 全局路由前綴
- 混合應用
- HTTPS 和多服務器
- 請求生命周期
- 常見錯誤
- 實例
- 遷移指南
- 發現
- 誰在使用Nest?