How to catch a sequelize connection error in case there is one?
I tried to do
var connection = new Sequelize("db://uri");
connection.on("error", function() { /* perhaps reconnect here */ });
but apparently this is not supported.
I wanted to do this because I think sequelize might be throwing an occasional unhandled ETIMEOUT and crashing my node process.
Currently I am using sequelize to connect a mysql instance. I only need it for like 2-3 hours and during that time I will be doing a many read queries. The mysql server will not be connected to anything else during that time.
Using sync() for this is considerably dangerous when using external migrations or when database integrity is paramount (when isn't it!)
The more up-to-date way of doing this is to use authenticate()
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Using sequelize sync method provides an easy way to catch the error.
The then block handles a Successful connection and the catch handles the rejection.To get a detailed reason for a failure access the error object.
example: error.message e.t.c
Hope this helps.
sequelize.sync().
then(function() {
console.log('DB connection sucessful.');
}).catch(err=> console.log('error has occured'));
Use sequelize sync for that
var Sequelize = require('sequelize');
sequelize = new Sequelize(config.database, config.username, config.password, {
'host' : config.host,
'dialect' : config.dialect,
'port' : config.port,
'logging' : false
})
sequelize.sync().then(function(){
console.log('DB connection sucessful.');
}, function(err){
// catch error here
console.log(err);
});
Related
I am currently working with node and mongoDB
here is my code
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
mongoose
.connect(
`mongodb+srv://OmniBotBuilder:${process.env.DBPASS}${process.env.DBUSER}.kx2vg.mongodb.net/${process.env.DBNAME}?retryWrites=true&w=majority`,
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
)
.catch(() => console.error("Unable to connect to DB"));
mongoose.connection.on("connected", () => {});
const Schema = mongoose.Schema;
const omniGamesSchema = new Schema({
discordId: Number,
steamId: Number,
});
const omniGamesModel = mongoose.model("omniGamesSchema", omniGamesSchema);
const createNewUser = (discordId, steamId) => {
const newUserMap = new omniGamesModel({
discordId: discordId,
steamId: steamId,
});
newUserMap.save((err) => {
if (err) {
console.error(err);
}
});
};
export { createNewUser };
and the error i am getting is this one
MongooseError: Operation omnigamesschemas.insertOne() buffering timed out after 10000ms
at Timeout. (C:\Users\dahiy\OneDrive\Desktop\bots\omni-games\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
This issue normally is caused because:
wrong auth, by the meaning the mongo path string is wrong so maybe double check your pass and username
check the allowed IP to access the database from the mongo website, if you want it to be accessed from everywhere just use IP: 0.0.0.0/0
Your internet connection might be slow to the point it cannot connect to the DB
Hope you found this helpful! :)
You can open https://cloud.mongodb.com/
Click connect Goto the Connect your application
Select Driver Node.js version 4.1 leter
Copy the link which you have to show than paste this link to your
project .env file now try to run application connect Database and
check.
I'm trying to connect to a PostgreSQL database using Knex.js, but I just can't get a connection to happen. The only exception I'm seeing is:
Error KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
I built this simple test script to make sure it wasn't part of our program:
const knex = require("knex")({
client: 'pg',
connection: {
host : 'localhost',
port: 5432,
database: 'postgres',
user: 'postgres',
password: 'password'
},
pool: {
afterCreate: (conn, done) => {
console.log("Pool created");
done(false, conn);
}
},
debug: true,
acquireConnectionTimeout: 2000
});
console.log("A")
const a = knex.raw('select 1+1 as result').then(result => console.log("A Success", result)).catch(err => console.log("A Error", err));
console.log("B")
const b = knex.select("thing").from("testdata").then(data => console.log("B Success", data)).catch(err => console.log("B Error", err));
console.log("C")
const c = knex.transaction(trx => {
trx.select("thing").from("testdata")
.then(data => {
console.log("C Success", data);
})
.catch(err => {
console.log("C Error", err);
});
})
.catch(err => {
console.log("C Error", err);
});
console.log("waiting on query")
// Promise.all([a, b, c]).then(() => {
// console.log("Destroying")
// knex.destroy()
// })
Which is producing the following output
A
B
C
waiting on query
A Error KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
at Client_PG.acquireConnection (E:\DEV\work\niba-backend\node_modules\knex\lib\client.js:347:26)
at runNextTicks (internal/process/task_queues.js:58:5)
at listOnTimeout (internal/timers.js:520:9)
at processTimers (internal/timers.js:494:7) {
sql: 'select 1+1 as result',
bindings: undefined
}
B Error KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
at Client_PG.acquireConnection (E:\DEV\work\niba-backend\node_modules\knex\lib\client.js:347:26) {
sql: undefined,
bindings: undefined
}
C Error KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
at Client_PG.acquireConnection (E:\DEV\work\niba-backend\node_modules\knex\lib\client.js:347:26)
at async Transaction.acquireConnection (E:\DEV\work\niba-backend\node_modules\knex\lib\transaction.js:213:28)
It's never calling the afterCreate method. I have tried it against both our dev database using settings that work for everyone else, and a locally running postgres installation with every combination of settings I could come up with. I even passed this off to another member of the team and it worked fine, so there's something up in my machine, but I have no idea what could be blocking it. I'm not seeing any connection attempts in the postgres logs, and I can't seem to get any better error messages to work off of.
If anyone could come up with things I can try, or ways to get more information out of Knex I would really appreciate it.
I traced the issue down to the verion of the 'pg' package we were using. Was using 7.18 and when I upgraded to the latest version (8.4) it started connecting. No idea why the 7.x version wasn't working.
I installed "pg": "^8.0.2" and created the database.js file with database credentials. But no matter what go wrong it never enters in the catch block to show error. Instead it always logs connected to the database. Can anyone point out what I'm doing wrong. Thank You!
Database.js
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'roothjk',
host: 'localhost',
database: 'sf',
password: 'admin',
port: 5432
});
try {
pool.connect()
console.log('connected to the db');
} catch (e) {
console.log('Error connecting to db');
}
connect returns a Promise, and then you move to the next statement. Instead, you should use the then and cath methods:
pool.connect()
.then(c => console.log('connected to the db'))
.catch(e => console.log('Error connecting to db'));
I am trying to use Sequelize to connect with a SQL Server 2012 database. When my connection string was clearly wrong, I was seeing ECONN REFUSED messages and timeout. Now, I am not getting any response, despite logging on success and fail, per this code:
import * as Sequelize from 'sequelize';
-- connection string redacted
let seqConn = new Sequelize("mssql://**;Initial Catalog=**;Persist Security Info=True;Integrated Security=SSPI; User ID=**; Password=**")
seqConn
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
I was previously using the syntax:
let seqConn = new Sequelize("DB", "Username", "Password",
{
dialect: 'mssql',
dialectOptions: {
instanceName: 'dev'
},
host: '**'
};
But I couldn't find a setting for integrated security or other fancy SQL Server things.
Regardless, my current connection string isn't erroring. But also, it is not saying the connection was established.
I tried passing my seqConn to a model to use it to retrieve a model:
getModel(seqConn): void {
console.log("Getting");
var model = seqConn.define("dbo.Model", {
modelID: Sequelize.INTEGER,
modelNo: Sequelize.INTEGER,
modelName: Sequelize.STRING(50),
modelAge: Sequelize.DATE
});
seqConn.sync().then(function() {
model.findOne()
.then( function (modelRes){
console.log("got a result!?");
console.log(modelRes.get("modelName"));
})
.catch( function (error){
console.log("it didn't work :( ");
});
});
console.log('after getter');
return;
}
I'm not confident that this is the right way to use sequelize, and I'm still establishing my project structure, but for now I expect to either see a "got a result" or an error, but nothing is logging here from either the then() or the catch(). The before/after getter logs are logging fine.
I have considered that it takes a long time to connect, but my IT says that he saw my successful connection in our SQL logs, and previously I was getting timeouts in about 15,000 ms, I think.
The problem was solved by including another NPM module: `sequelize-msnodesqlv8'
And then the code to connect to Sequelize looked like:
var Sequelize = require('sequelize');
var seqConn = new Sequelize({
dialect: 'mssql',
dialectModulePath: 'sequelize-msnodesqlv8',
dialectOptions: {
connectionString: 'Driver={SQL Server Native Client 11.0};[REDACTED]'
}
});
seqConn
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
I am using mongoose for connecting node.js with mongoDB, now i wrote below query
var trans = new transmodel({method: method, trans_id: r});
trans.save(function(err) {
if (err) {
console.error("Razor_pay_webhook Error 4 err: " + err);
res.write('statusCode: 200');
res.end();
} else {
res.write('statusCode: 400');
res.end();
}
});
I thought when my mongodb cluster will be down then i will get 'err' while executing above mongoose query, but when i ran above query while my mongo cluster was down nothing happened(No err was called). Can anyone please tell me how can i catch the error if my mongodb server is down inside my query. Also for reconnecting again with my cluster i have set below parameters but my node server is not trying to reconnect again with my mongodb server i don't know what's going wrong.
var mongoose = require('mongoose');
var config = require('./config/database.js');
var DB_URL = config.db.url;
mongoose.connection.on("connected", function(ref) {
console.log("Connected to " + " DB!");
});
mongoose.connection.on("error", function(err) {
console.error('Failed to connect to DB ' + ' on startup ', err);
if (err) {
return next(err);
}
});
mongoose.connection.on('disconnected', function(err) {
console.log('Mongoose default connection to DB :' + ' disconnected');
if (err) {
return next(err);
}
});
var gracefulExit = function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection with DB :' + ' is disconnected through app termination');
process.exit(0);
});
}
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
exports.con_close = function () {
console.log('Mongoose connection disconnected');
mongoose.connection.close();
}
var options = {
server: {
socketOptions: {
keepAlive: 1000,
connectTimeoutMS: 30000
}
},
replset: {
rs_name: 'replicaset',
auto_reconnect:true,
socketOptions: {
keepAlive: 1000, // doubt about it
connectTimeoutMS: 30000
}
},
user: 'root',
pass: 'G3saGT2Y',
auth: {
authdb: 'admin'
}
}
mongoose.connect(DB_URL, options, function(err) {
console.log('ho rha hai');
if (err) {
console.log('error connection to mongo server!');
console.log(err);
}
});
You are using mongoose, it emits events (the EventEmitter pattern) when the database is down and when the database is reconnecting and up again.
from mongoose code found here we can see that the library db connection - connection.js
has the following events that are emitted:
* #param {Mongoose} base a mongoose instance
* #inherits NodeJS EventEmitter
http://nodejs.org/api/events.html#events_class_events_eventemitter
* #event connecting: Emitted when connection.{open,openSet}() is executed on this connection.
#event connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
#event open: Emitted after we connected and onOpen is executed on all of this connections models.
#event disconnecting: Emitted when connection.close() was executed.
#event disconnected: Emitted after getting disconnected from the db.
#event close: Emitted after we disconnected and onClose executed on all of this connections models.
#event reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
#event error: Emitted when an error occurs on this connection.
#event fullsetup: Emitted in a replica-set scenario, when primary and at
least one seconaries specified in the connection string are connected.
#event all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
When the database is down you will receive two events:
1. disconnected
2. error (the error that driver encountered)
When the database is up again you will receive the reconnect event.
So you don't need to try catch the error rather you should listen to these events.
More helpful information about connection failures and reconnecting can be found here.
This article explain how to use and configure the autoReconnect and the bufferMaxEntries according to your settings.