如何处理 MongoDB 的断开连接错误 [英] how to handle disconnect error for MongoDB

查看:45
本文介绍了如何处理 MongoDB 的断开连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Node.js 进程中看到了这个未捕获的异常:

<块引用>

未捕获的异常:{ 错误:读取 ETIMEDOUT在 TCP.onStreamRead (internal/stream_base_commons.js:162:27)name: 'MongoNetworkError',错误标签:['TransientTransactionError'],[Symbol(mongoErrorContextSymbol)]: { isGetMore: true } }

我尝试使用以下方法捕获/捕获它:

import * as mdb from 'mongodb'const d = new mdb.MongoClient(...);d.on('error', () => {...});//把它困在这里

但这似乎无法捕获错误.有人知道我该怎么做吗?

解决方案

使用 MongoDB 驱动程序时有 2 种不同类型的连接错误:

  1. 初始连接期间的错误
  2. 初始连接建立后的错误

'error' 事件用于处理 (2).看起来您正在寻找处理初始连接错误的正确方法.对于那些,您应该在 connect() 返回的承诺上将回调传递给 connect().catch().>

const NUM_RETRIES = 3;常量延迟 = 1000;让错误=空;for (让 i = 0; i  0) {await new Promise(resolve => setTimeout(resolve, i * delay));}尝试 {等待 mdb.MongoClient.connect(uri);休息;} 抓住(错误){错误 = 错误;}}

I am seeing this uncaught exception in my Node.js process:

Uncaught exception: { Error: read ETIMEDOUT
    at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: { isGetMore: true } }

I tried capturing/trapping it using:

import * as mdb from 'mongodb'
const d = new mdb.MongoClient(...);
d.on('error', () => {...});  // trap it here

but that does not seem to be able to trap the error. Anyone know how I can do so?

解决方案

There are 2 distinct types of connection errors when using the MongoDB driver:

  1. Errors during initial connection
  2. Errors after initial connection is established

The 'error' event is used to handle (2). It looks like you're looking for the correct way to handle initial connection errors. For those, you should either pass a callback to connect() or .catch() on the promise that connect() returns.

const NUM_RETRIES = 3;
const delay = 1000;
let error = null;
for (let i = 0; i < NUM_RETRIES; ++i) {
  if (i > 0) {
    await new Promise(resolve => setTimeout(resolve, i * delay));
  }
  try {
    await mdb.MongoClient.connect(uri);
    break;
  } catch (err) {
    error = err;
  }
}

这篇关于如何处理 MongoDB 的断开连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆