I'm trying to fix an error UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED when I make an axios call to fetch user data from mongoose query without internet connection. I've tried to wrap both the mongoose query User.findOne() and mongoose.connect() with try catch, but the error still remain.
(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv
ECONNREFUSED _mongodb._tcp.cluster1-94jth.mongodb.net [0] at
QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) [0] (node:3966)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch(). (rejection id: 1) [0] (node:3966) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
FRONT-END
client.js
try {
const res = await axios.get('/auth/user?', {
params: {
refreshToken: refreshToken,
userID: userID
}
}
);
console.log(res.data);
} catch (error) {
if(error.toJSON().message === 'Network Error'){
alert('no internet connection');
}
}
BACK-END
auth.routes.js
auth.get(
'/user',
async(req, res)=>{
try {
const {userID, refreshToken, uniqueDeviceID, authTimestamp} = req.query;
const existingUser = await User.findOne({
$and: [
{'user_id': userID},
{'refresh_token': refreshToken}
]
});
res.send(existingUser);
} catch (error) {
console.log(error);
}
}
);
server.js
try {
mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
console.log('Database Connected');
} catch (error) {
console.log(error);
}
Wrapping mongoose.connect with try/catch will not work because its no doing async/await.
You should:
mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
.then(() => console.log('Database Connected'))
.catch(error=> console.log(error));
try/catch won't work with an asynchronous function without await
so to catch an error from asynchronous function:
try {
await someAsyncFunction();
} catch (e) {
//...
}
or you could use catch method from Promise or even use callbacks.
Related
I'm trying to handle errors using express middleware, with these lines I have the following errors
user.js controller
app.post('/create', async (req, res, next) => {
const data = await User.create(req.body)
.catch((err) => next(err));
res.status(201).json({ ok: true, ...data });
});
user.js model
UserSchema.statics.create = async function createUser(data) {
delete data.role;
const user = await new this(data).save();
return { token: user.newToken(), user };
};
app.js
app.use((err, req, res, next) => {
res.status(err.code || 400);
res.json({ ok: false, err: err.message });
});
Errors
(node:3304) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
...
(node:3304) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 9)
(node:3304) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
After to proof with try/catch in the user.js controller i don't have any error, but in the express documentation use try/catch is not recommended.
app.post('/create', async (req, res, next) => {
try {
const data = await User.create(req.body)
res.status(201).json({ ok: true, ...data });
} catch (err) {
next(err);
}
});
Any ideas?
You either use await or then/catch:
app.post('/create', async (req, res, next) => {
User.create(req.body)
.then(data => {
res.status(201).json({ ok: true, ...data });
})
.catch((err) => next(err));
});
I'm setting up a login system with nano, passport and couchdb. Things are mostly working but when couchdb is offline I'm given this error:
(node:893) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:5984
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
(node:893) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:893) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My code:
const LocalStrategy = require('passport-local').Strategy;
const nano = require('nano')('http://admin:password#localhost:5984');
const users = nano.use('users');
const bcrypt = require('bcrypt');
module.exports = function(passport) {
passport.use(new LocalStrategy(
function(username, password, done) {
users.view('auth', 'auth', {'key': username, 'include_docs': true})
.then(dbresponse => {
if (dbresponse.rows.length === 1) {
const user = dbresponse.rows[0].doc;
bcrypt.compare(password, user.password, function(err, result) {
if(result === true) {
done(null, user)
} else {
done(null, false)
}
});
} else {
done(null, false);
}
})
}
));
};
I can't have the entire app stop working when the database is offline. I'd like to handle this error somehow but I can't figure out how.
In my Node.js backend, I have an endpoint where user profile info is updated. I want to send user an error response if the new email is already in the database. However, though I have set up a try-catch in place, I still can't catch the error. Instead, the server just crashes with the following mongoose error message. I receive an error response on the front end, but after a very long time from when the error happened. All helpful advice is highly appreciated.
(node:11864) UnhandledPromiseRejectionWarning: MongoError: E11000
duplicate key error collection: testing.users index: email_1 dup key:
{ : "test#gmail.com" } ... (node:11864)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise
rejection, use the CLI flag --unhandled-rejections=strict (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1)
UpdateProfile in UserController.js
updateProfile: (id,fname,lname,email,mobile,address,next) => {
let args = {fname,lname,email,mobile,address}
try{
User.findOneAndUpdate({ "_id": id },
{ "$set": Utils.removeNullsFromObject(args)},
{new: true, useFindAndModify: false}).then(function(updatedUser, err){
if(err) {
console.log(err);
next(err,null)
} else {
next(null,updatedUser)
}
);
}
catch(err){
console.log(err);
next(err,null)
}
}
Try...catch will work with async/await and not with promise...then. promise...then has special block called catch which can be used as,
updateProfile: (id,fname,lname,email,mobile,address,next) => {
let args = {fname,lname,email,mobile,address}
User.findOneAndUpdate({ "_id": id },
{ "$set": Utils.removeNullsFromObject(args)},
{
new: true, useFindAndModify: false
}).then(updatedUser => {
next(null,updatedUser)
).catch(err =>{
console.log(err);
next(err,null)
})
}
and if you want to use async/await, then,
updateProfile: async (id,fname,lname,email,mobile,address,next) => {
let args = {fname,lname,email,mobile,address}
try{
const updatedUser = await User.findOneAndUpdate({ "_id": id },
{ "$set": Utils.removeNullsFromObject(args)},
{
new: true, useFindAndModify: false
})
next(null,updatedUser)
} catch(err) {
console.log(err);
next(err,null)
})
}
For more details, you can refer https://javascript.info/promise-error-handling
I have created an app on heroku server and installed Postgres free add-on. Now I have a nodejs project in which I am connecting this database using pg modules. So for this I have created
db-connect.js
var { Pool } = require('pg');
var nodeEnvFile = require("node-env-file");
nodeEnvFile(".env");
var config = {
user: process.env.DB_USER,
host: process.env.DB_IP,
database: process.env.DB,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
max: 10, // max number of connection can be open to database
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};
var pool = new Pool(config);
module.exports = {
query: (query, callback) => {
console.log(query);
pool.connect().then(client => {
return client.query()
.then((result) => {
client.release();
console.log(result.rows)
callback(null, result.rows[0]);
})
.catch(err => {
client.release();
callback(err, null);
});
})
}
}
and then in the API layer, I have imported this file
const db = require("../db/db-connect");
and used like this
router.get("/getdata/", (req, res) => {
var query = "query";
db.query(query, (err, result) => {
if (err) {
res.status(400).send(err);
}
res.send(result);
})
});
and this was showing following error
(node:1984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): error: no pg_hba.conf entry for host "157.39.161.5", user "ltolmhjmwnfokl", database "den55ln368anf8", SSL off
(node:1984) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
select * from get_notifications('sidhu',0,1);
(node:1984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): error: no pg_hba.conf entry for host "157.39.161.5", user "ltolmhjmwnfokl", database "den55ln368anf8", SSL off
and then I enabled ssl option in the config object
var config = {
user: process.env.DB_USER,
host: process.env.DB_IP,
database: process.env.DB,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
max: 10, // max number of connection can be open to database
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
ssl: true
};
but now this is showing
(node:252) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'submit' of undefined
(node:252) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
ServiceUnavailableError: Response timeout
at IncomingMessage.<anonymous> (D:\PROJECTS\PuWifi\GitHubForHeroKu\PuWifi\node_modules\connect-timeout\index.js:84:8)
at emitOne (events.js:116:13)
at IncomingMessage.emit (events.js:211:7)
at Timeout._onTimeout (D:\PROJECTS\PuWifi\GitHubForHeroKu\PuWifi\node_modules\connect-timeout\index.js:49:11)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
what is the issue? Am I missing something?
Actually, I was missing to pass the query in client.query(). It should be client.query(query). Here is the code
module.exports = {
query: (query, callback) => {
console.log(query);
pool.connect().then(client => {
return client.query()
.then((result) => {
client.release();
console.log(result.rows)
callback(null, result.rows[0]);
})
.catch(err => {
client.release();
callback(err, null);
});
})
}
}
The other is to use pool.query
module.exports = {
query: (query, callback) => {
console.log(query);
pool.query(query).then(response => {
callback(null, response.rows);
}).catch(err => {
callback(err, null);
})
}
}
For detail: https://github.com/brianc/node-postgres/issues/1597#issuecomment-375554709
Need a little help. Been learning NodeJS. And so far so good. But I am running into an issue when I try to create a new ToDo object that's associated with an authenticated user.
I get the following error
(node:54162) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:54162) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is the offending code:
app.post('/todos', authenticate, (req, res) => {
var todo = new Todo({
text: req.body.text,
_creator: req.user._id
});
todo.save().then(() => {
res.send(todo);
}).catch((e) => {
res.status(400).send(e);
});
})
I am not sure what I am missing. I've read in certain places about try catch mismatches. But I am still not sure.
Just for more context, I have also added my authenticate.js
var {User} = require('./../models/user');
//Definining endpoint authentication middleware
var authenticate = (req, res, next) => {
var token = req.header('x-auth');
User.findByToken(token).then((user) => {
if(!user) {
return Promise.reject();
}
req.user = user;
req.token = token;
next();
res.send(user);
}).catch((e) => {
res.status(401).send();
});
};
module.exports = {authenticate};