UnhandledPromiseRejectionWarning doesn't reach Catch - mongodb

This is my code:
db.Registration.model.countDocuments()
.then(function (count) {
return res.status(200).send({ count });
})
.catch(function (err) {
console.log('errrr', err);
if (err)
return res.status(500).sendStatus(err);
else
return res.status(200).sendStatus({ count });
})
I get the following error:
Express server running on *:5000
(node:8864) UnhandledPromiseRejectionWarning: Error: querySrv ENOTFOUND _mongodb._tcp.cluster0-shard-00-00-jjbdh.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
(node:8864) 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:8864) [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.
Why catch is not working and I get this error instead?

Related

Unhandled promise rejection. This error originated either by throwing inside of an async function

i want to send the updatedUser informations plus an image file in the response but I get this kind of error: " 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)
(node:69044) [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.".i googled this error but nothing helpful, so this is my code :
userRouter.post("/upload/:id",async(req, res)=> {
const user_id = req.params.id;
const pp = req.files.productImage;
const {data} = pp;
const namePp = uuidv4() + '.' + pp.name.split('.').pop();
pp.mv("./picturesProfile/" + namePp);
const updatedUser = await User.findByIdAndUpdate(user_id, {new: true},{image: namePp}, function (err, docs) {
if(err) {
console.log(err)
} else {
return docs
}
})
console.log(updatedUser)
res.send({updatedUser,pp});
})
This one will work you!
const doc = await User.findByIdAndUpdate(user_id,
{ $set: { "image": namePp }},
{
new: true,
runValidators : true
});

Mongoose Connection Error in Stackblitz - Mean app

I am trying to create a mean app. I am receiving errors while connecting mean app with MongoDb using mongoose. I am using "express": "^4.17.1", and "mongoose": "^6.0.7".
const mongoose = require('mongoose');
// Connecting to MongoDb
mongoose.connect(
'mongodb+srv://MongoDb:<password>#cluster0.xfdie.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDb');
});
mongoose.connection.on('error', (err) => {
if (err) {
console.log('Error in MongoDb Connection' + err);
}
});
It's working fine with the localhost but I am receiving the following error in Stackblitz.
Error in MongoDb ConnectionTypeError: this._handle[e] is not a function
(node:13) UnhandledPromiseRejectionWarning: TypeError: this._handle[e] is not a function
at Resolver.querySrv [as resolveSrv] (https://file-sharing-portal.jw.staticblitz.com/blitz.fa2fa735bbb029186c23972eb56445ed5c5fdef5.js:6:585119)
at Object.resolveSRVRecord (/home/projects/file-sharing-portal/node_modules/mongodb/lib/connection_string.js:55:9)
at Object.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/operations/connect.js:41:36)
at eval (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:127:23)
at Object.maybePromise (/home/projects/file-sharing-portal/node_modules/mongodb/lib/utils.js:518:5)
at MongoClient.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:126:24)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:785:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:776:19)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/index.js:328:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13) 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)
(node:13) [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.
Please assist.
I asked for help in stackblitz-help channel in discord for the same and was informed that Mongoose isn't supported yet : https://github.com/stackblitz/core/issues/251
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect("CONNECTION_STRING", "OPTIONS", (error) => {
if (error)
console.log("Connection error - ", error);
else
console.log("MongoDB connection established");
});
let server = http.createServer(app);
server.setTimeout(500000);
server.listen(3000);
try with above code snippets

What is the proper way of detecting network errors in stream downloads using Axios in Nest.js?

I'm working with the HttpService module from Nest.js to make the HTTP calls. I'm able to download an image from https://unsplash.com; when there is no network interruptions the code is working as expected.
This is the code I have for making the download call and start writing into the desired file
const urlDownload = 'https://unsplash.com/photos/xiie4XeSzTU/download?force=true';
let response = await this.httpService.get(urlDownload, {
responseType: 'stream'
}).toPromise();
response.data.pipe(writer);
And this is the code where I'm trying to handle the possible events of the writer and returning a response
let downloadFile = path.resolve(__dirname,'../../files/landscape.jpg');
let writer = fs.createWriteStream(downloadFile);
return new Promise((resolve, reject) => {
writer.on('finish', ()=>{
resolve('Image downloaded');
});
writer.on('error', ()=>{
reject('Image downloaded failed');
});
});
I'm deliberately turning off the wifi during the download to try the server response with Image downloaded failed (what I have in the writer error handler), but instead I'm getting an 500 statusCode, internal server error. When I go to the Nest console to whatch the error it appears
[Nest] 11220 - 2020-05-22 18:16:45 [ExceptionsHandler] getaddrinfo ENOTFOUND unsplash.com +439536ms
Error: getaddrinfo ENOTFOUND unsplash.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)
How can I solve this and catch correcty the network error from Nest to return a friendly message?
I could solve it. I let it here with the hope of helping somebody in the future.
It is not firing the error handler function because that handler is attached to the writter, and there is not writting error, it just stops writing because the cut of the connection but that is not an error.
I re-writed the response variable to stop being a promise and better I started treating it like an observer.
let response = this.httpService.get(urlDownload, {
responseType: 'stream',
});
And then it is the response in previus Promise format
return new Promise((resolve, reject) => {
writer.on('error', () => {
resolve('error due to, possibly, an unexisting file path');
})
response.subscribe({
next(response) { response.data.pipe(writer) },
error(err) {
console.error('More details: ' + err);
resolve('Error in the download :/')
},
complete() { resolve('Completed'); }
})
});
I'm not using the reject function of the promise but it is perfectly doable

UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND api.sendgrid.com api.sendgrid.com:443 when sending mail

UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND api.sendgrid.com api.sendgrid.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
(node:6768) 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:6768) [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.
Please could you be more elaborate or better still add code snippet of your code for clearer understanding.
But from what I'm suspecting, I think there is an asynchronous call that you made that was not handled properly which might be that you didn't catch an error exception after the call.
Always remember that transport.sednmail() is an asynchronous function and it returns a promise.
See example below:
// With ".then" function
transport.sendMail(email)
.then(response => console.log(response))
.catch(error => console.log(error))
// With Callback function
transport.sendMail(email, (error, response) => {
if(error) {
console.log(error);
}
else{
console.log(response);
}
})
I hope this might be of little help to fixing the issue.

How to use Mongoose to connect mongo-atlas db?

I'm following this tutorial to setup the mongo atlas db.
https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/
But on the setup of connection, I got error like
(node:60566) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [find] on [admin.sample_airbnb]
at queryCallback (/Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/cursor.js:223:25)
at /Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/connection/pool.js:541:18
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:60566) 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:60566) [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.
It seems atlas db is using "admin" collection by default, how can I change it to "sample_airbnb" collection?
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/a?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
Listing.findOne({}).then((r) => {
console.log(r);
})
})
(node:60566) You need to add "admin permission"s to be able to query the db. This will be under "security" tab then "Database Access". "Add new user" button (which is then used in your connection string).
".mongodb.net/a?" needs to be ".mongodb.net/sample_airbnb?"
(node:60566) Use try catch e.g.
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/sample_airbnb?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
try {
const listings = await Listing.findOne({});
res.json(listings);
} catch (err) {
res.json({ message: err });
}
});
});