How to handle promise rejection in this case - node.js

In here i want to add new field in collection User (User.facebook.botLink)
but i get an error.
Code where i get error looks like this:
app.post('/savelink/', async (req, res, next) => {
try{
console.log("================USER FACEBOOK ===============" + user.local.email)
const {link} = req.body;
console.log(link);
User.update(
{email: user.facebook.email},
{botLink : link},
{multi:true},
function(err, numberAffected){
});
res.status(200).send(link);
}
catch(e){
next(error);
}
});
Error i'm getting:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: error is not defined
(node:6032) [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.

try this
catch(e){
next(error);
}
to
catch(e){
next(e);
}

You can aslo do a try/catch...finally.
Note that the finally block will be executed regardles of the result of try/catch.
For more einformation, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
try{
// some code
}
catch(error){
// handle error
}
finally {
// do something else
}

Related

Unhandled Promise Rejection Warning Occured

I want to create Product Categories , so i handle it in productController class database call in productCatService class. I added JS promise to this . now it gives following error.
productCatController.js
module.exports.createProductCat = async (request, response)=> {
let result = await productCatService.createProductCat(productCatData);
if (result) {
responseService.successWithData(response, "Product Category Created");
} else {
responseService.errorWithMessage(response, result);
}
}
productCatService.js
module.exports.createProductCat = (productCatData) => {
let productCat = {
name: productCatData.name,
desc: productCatData.desc,
count:productCatData.count,
status : productCatData.status
};
return new Promise((resolve,reject)=>{
ProductCategory.create(productCat).then(result => {
resolve(true);
}).catch(error => {
reject(false)
})
});
}
Error
(node:18808) UnhandledPromiseRejectionWarning: false
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a p
romise 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: 2)
(node:18808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a no
n-zero exit code.
Never use await without try/catch. You don't have to try/catch every await, but somewhere down the call stack there needs to be a try/catch block.
You don't need try/catch here, just return the promise from ProductCategory.create()...
// productCatService.js
module.exports.createProductCat = (productCatData) => ProductCategory.create({
name: productCatData.name,
desc: productCatData.desc,
count: productCatData.count,
status: productCatData.status
});
...but you definitely need try/catch here, as this function is the bottom of the stack for this operation, and it is responsible for signifying overall success or failure to the caller.
// productCatController.js
module.exports.createProductCat = async (request, response) => {
try {
await productCatService.createProductCat(productCatData);
responseService.successWithData(response, "Product Category Created");
} catch (err) {
responseService.errorWithMessage(response, err);
}
}
Also don't use new Promise() for operations that already are promises. Keep using the promise you already have. Wrapping new Promise() around existing promises is a source of useless bloat, and it can introduce subtle bugs. Avoid.

Trying to update a table - Error: Unhandled promise rejection node.js

I'm trying to update a user with a hashed password when I start the app.
So I wrote this in app.js:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219)
.catch(console.log('err'));
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
And I got this error:
(node:6800) UnhandledPromiseRejectionWarning: TypeError: Utilisateur.query is not a function
at D:\Project\***\backend\app.js:48:37
(node:6800) 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:6800) [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.
use this code for catching the error:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
try {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219);
} catch (e) {
console.log(e);
}
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
you tried to mix "then().catch()" with "await", which will not work.

Retrieving JSON data from an Axios response

I'm using TypeScript to create a Node.js application and I want to retrieve JSON data from an external API. I have a demo version of the code I'm using, can't put my actual codebase up.
private async getData() {
return await Axios.get(
`http://dummy.restapiexample.com/api/v1/employees`
).then(response => {
return response.data;
});
}
getReleaseResults() {
this.getData().then(responseData => {
responseData.data.data.forEach((element: any) => {
console.log(element);
});
});
}
The error message I get is: (node:6068) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at C:\Users\Caoilinn.Hughes\OneDrive\Documents\TypeScript Demos\Azure Test Result Email Extension\emailAzureExtension\app\out\js\apiCaller.js:43:36
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:6068) 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:6068) [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.
If I don't have the for each and replace it with
console.log(responseData.data.data)
I don't get any issues. FYI the result set has a data property hence the "data.data"
The problem is that you are already returning response.data from your get function and then again you are doing data.data which would not work.
see this. Remove extra data.
getReleaseResults() {
this.getData().then(responseData => {
responseData.data.forEach((element: any) => {
console.log(element);
});
});
}
Add catch block to get the error if there is any. What is the expected response ? try to log it.
return await Axios.get(
`http://dummy.restapiexample.com/api/v1/employees`
).then(response => {
console.log(response);
return response.data;
}).catch(err => console.log(err));

mongoose (check and save if new)

I am getting this error and the request should only be happening once,
UnhandledPromiseRejectionWarning: ParallelSaveError: Can't save() the same doc multiple times in parallel. Document: 5e269bd87c588b6285499c14
at ParallelSaveError.MongooseError [as constructor] (/root/react-passport-example/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at new ParallelSaveError (/root/react-passport-example/node_modules/mongoose/lib/error/parallelSave.js:18:17)
at model.Model.save (/root/react-passport-example/node_modules/mongoose/lib/model.js:434:20)
at /root/react-passport-example/server/routes/public_api.js:64:21
at /root/react-passport-example/node_modules/mongoose/lib/model.js:4590:16
at /root/react-passport-example/node_modules/mongoose/lib/query.js:4351:12
at cb (/root/react-passport-example/node_modules/mongoose/lib/query.js:1900:14)
at result (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:75:17) at executeCallback (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:68:9)
at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at cursor.close (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:36:13) at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at completeClose (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:859:16)
at Cursor.close (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:878:12)
at cursor._next (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:35:25) at self._initializeCursor (/root/react-passport-example/node_modules/mongodb/lib/core/cursor.js:750:9) (node:25221) 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:25221) [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 am wondering if there is a better and cleaner way to do the following.
router.post('/login', (req, res) => {
var query = req.body,
add = new LoginModel(query);
console.log(query.email);
LoginModel.find({uid : req.body.uid}, function (err, docs) {
if (docs.length){
console.log(err);
res.status(200).json({
message: "ERROR USER ALREADY EXISIT",
// user values passed through from auth middleware
//user: req.user
});
}else{
add.save(add.save(function (err, query) {
if (err) return console.error(err);
}));
}
});
});
This is happening because you are using add.save twice in your code. Hope below code works for you.
add.save((err, query) => {
if (err) {
return err;
} else {
return result;
}
});

proxyReq.setHeader can not set headers after they are sent

i am building a node.js proxy and i want to add a conditional header
proxy.on('proxyReq', (proxyReq, req, res) => {
const realIP = parseHttpHeader(req.headers['x-real-ip'])[0];
const path = parseHttpHeader(req.headers['x-original-uri'])[0];
pAny([
check_ip(realIP) ,
check_path(path) ,
check_geo(realIP)
]).then(result => {
console.log (result , "result " )
if (result) {
proxyReq.setHeader('namespace' , 'foo');
} else {
proxyReq.setHeader('namespace' , 'bar'); }
console.log('sending req ')
});
});
.
async function check_ip(realIP) {
try {
const result = await ipModel.findOne({ip: realIP}).exec()
console.log(realIP , result , "ip")
if (result) {
return true
} else {
return false
}
} catch (e) {
throw e;
}
}
and it works just fine till i use the methos check_ip then i get the error
(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) 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:3793) [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.
as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await
make the check_ip return a promise and try
function check_ip(realIP) {
return ipModel.findOne({ ip: realIP }).exec();
}

Resources