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

如何访问node-mongodb-native的错误码列表?

Node.js中MongoDB错误码的处理问题及解决方案

问题描述

在Node.js应用中使用MongoDB时,希望捕获MongoServerError后根据错误的code执行对应逻辑(比如处理NamespaceNotFound错误),但发现官方库内部定义的错误码列表并未暴露给使用者。虽然抛出的错误实例里能直接获取code和codeName字段,但不想在代码中重复定义这些错误码,疑惑是否有遗漏的方法?

错误示例:

MongoServerError: ns not found
    at Connection.onMessage (/home/alex/nodejs-project/node_modules/mongoose/node_modules/mongodb/src/cmap/connection.ts:438:20)
    at MessageStream.<anonymous> (/home/alex/nodejs-project/node_modules/mongoose/node_modules/mongodb/src/cmap/connection.ts:256:56)
    at MessageStream.emit (node:events:513:28)
    at MessageStream.emit (node:domain:489:12)
    at processIncomingData (/home/alex/nodejs-project/node_modules/mongoose/node_modules/mongodb/src/cmap/message_stream.ts:193:14)
    at MessageStream._write (/home/alex/nodejs-project/node_modules/mongoose/node_modules/mongodb/src/cmap/message_stream.ts:70:5)
    at writeOrBuffer (node:internal/streams/writable:391:12)
    at _write (node:internal/streams/writable:332:10)
    at MessageStream.Writable.write (node:internal/streams/writable:336:10)
    at Socket.ondata (node:internal/streams/readable:754:22) {
  ok: 0,
  code: 26,
  codeName: 'NamespaceNotFound',
  [Symbol(errorLabels)]: Set(0) {}
}

解决方案

目前mongodb官方Node.js驱动确实未将内部错误码常量列表暴露给外部,不过可以通过以下几种方式优雅处理:

  • 直接使用codeName判断
    错误实例自带的codeName是语义化字符串(如NamespaceNotFound),用它判断比数字code更易读,维护性更强,这也是更推荐的方式:

    try {
      // 执行MongoDB操作
    } catch (err) {
      if (err instanceof MongoServerError) {
        switch (err.codeName) {
          case 'NamespaceNotFound':
            // 处理命名空间不存在的逻辑
            break;
          case 'DuplicateKey':
            // 处理唯一键冲突的逻辑
            break;
          // 按需添加其他错误类型处理
        }
      }
    }
    
  • 封装自定义错误码映射
    如果偏好使用数字code,可以只封装业务中需要用到的错误码,避免全量重复定义:

    const MONGO_ERROR_CODES = {
      NamespaceNotFound: 26,
      DuplicateKey: 11000,
      // 按需添加其他需要处理的错误码
    };
    
    try {
      // 执行MongoDB操作
    } catch (err) {
      if (err instanceof MongoServerError && err.code === MONGO_ERROR_CODES.NamespaceNotFound) {
        // 处理逻辑
      }
    }
    
  • TypeScript类型提示辅助
    若使用TypeScript,可导入错误码的类型定义获得提示,但仅用于编译时校验,无法在运行时直接使用:

    import { MongoServerError } from 'mongodb';
    import type { ServerErrorDescription } from 'mongodb';
    
    try {
      // 执行MongoDB操作
    } catch (err) {
      if (err instanceof MongoServerError) {
        // 此处可获得code和codeName的类型提示
        if (err.codeName === 'NamespaceNotFound') {
          // 处理逻辑
        }
      }
    }
    

补充说明

官方未暴露错误码常量,主要是因为MongoDB的错误码列表会随版本迭代变化,直接暴露可能引发兼容性问题。而codeName语义化更强,相比数字code更稳定,是官方推荐的错误判断方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:15:32