How to handle UnhandledPromiseRejectionWarning in fetch API - javascript

I am using Javascript fetch API to post data to a json server. But I am getting UnhandledPromiseRejection Warning. Below is the code, plese help in finding the issue in the code.
function addFavourite(movieid) {
if (!favMovies.find(x => x.id == movieid)) {
let movie=movies.find((x)=>x.id==movieid);
//console.log(movie);
//addFavourite(movie);
return fetch("http://localhost:3000/favourites", {
method: "POST",
headers:{
"Contenet-Type": "application/json"
},
body: JSON.stringify(movie),
}).then((response) => {
favMovies.push(movie);
return response.json();
}).then((response)=>{
return response;
}).catch((error)=>{
return (error);
});;
} else {
throw new Error('Movie is already added to favourites');
}
}
(node:7358) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): AssertionError: AssertionError: expected
{ Object (voteCount, id, ...) } to deeply equal [ Array(2) ]: expected
{ Object (message, showDiff, ...) } to equal null (node:7358)
[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.

Related

UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function (NodeJS- Sequelize)

I'm following a tutorial on NodeJs on youtube, but when it comes to deleting users by id, it doesn't work like what's on the tutorial. But on that video everything seems to work perfectly. This is my code. Where am I wrong? Looking forward to everyone's comments.
let deleteUserByID = (userId)=>{
return new Promise(async(resolve, reject)=>{
try{
let user = await db.User.findOne({
where: {id: userId}
})
if(user){
await user.destroy();
}
resolve();
}catch(e){
reject(e);
}
})
}
And this is the error displayed on the terminal screen:
(node:11140) UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function
at...
at...
at...
...
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11140) 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:11140) [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 a while of searching on the internet, i found the solution, everything is working and seems to be fine, anyone can refer to it if they have the same error as mine.
Upvote if it works for you
let deleteUserByID=(userId)=> {
return db.User.destroy({ where: { id: userId } })
.then(rows => Promise.resolve(rows === 1))
}
Or another solution:
let deleteUserByID = (userId) => {
return new Promise(async (resolve, reject) => {
await db.User.findOne({
where: {
id: userId
}
})
await db.User.destroy({
where: {
id: userId
}
})
resolve({
errCode: 0,
message: `The user is deleted`
})
})
}

UnhandledPromiseRejectionWarning error in Expess

const Car = mongoose.model('Car', new mongoose.Schema({
name: {
type: String,
required: true,
}
}));
router.put('/:id', async (req, res) => {
const { error } = joiValidator(req.body);
if (error) return res.status(400).send(error.details[0].message)
try {
const car= await Car.findByIdAndUpdate(req.params.id, { name: req.body.name }, {new: true })
} catch (error) {
return res.status(404).send('not found.');
}
res.send(car);
})
i am successfully connected to mongoDB using mongoose, its only when i try to mock an error by giving a wrong id as an input i get the following error, even though i handled async and await with the trycatch block
(node:19392) 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:19392) [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.
This is mainly because you are using try an catch after an if. In javascript the way of reading code is asynchronous so, if and try are executed at the same time. Also, you donĀ“t need to use an async function here, as you are only calling one promise.
Here I let you a simpler code without async.
router.put("/:id", (req, res) => {
const { error } = joiValidator(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
} else {
Car.findByIdAndUpdate(req.params.id,{ name: req.body.name },{ new: true },(err, car) => {
if (err) return res.status(404).send({ message: 'Not found', err });
return res.status(200).send(car);
}
);
}
});

UnhandledPromiseRejectionWarning when using .reduce

const sendData = (response, language, locale) => {
try {
console.log(response.reduce((prev, curr) => prev + curr.confirmed, 0));
} catch (error) {
console.error('error');
}
};
and my fetch function:
const fetchGeneralData = async (param) => {
try {
let res = await axios.get(
`https://localhost/api/${param}`,
);
msg.reply(sendData(res.data.results), language, momentLocale);
} catch (error) {
msg.reply(language.errorMessage);
console.error(error, 'Error on fetchGeneralData');
}
};
The console.log shows me the correct value but for some reason, I still getting the errors.
I have tried adding async/await inside sendData but it did not work. My fetchGeneralData func works fine when i'm trying to return the date without modify it.
Here is the full message:
(node:5500) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: t.match is not a function
(node:5500) 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:5500) [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 catch inside axios in then method in node js

after I hit the below api call I am getting errors.
(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:5548) [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.
so I put try catch inside my then method but still I am not able to catch the errors inside my catch.
I debugged by putting console console.log("try catch error--->", error), but still no help
can you let me know whether I have added try and catch properly inside my then method.
providing my code snippet below
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
console.log("jwt then----->", jwtResponse.data.jwt);
var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
// var jwtToken = `Bearer ewefewehjefwwe wehwefwefwef uih uihu`;
console.log('then formatUrl --->', formatUrl);
axios.get(formatUrl, {
headers: {
"Authorization": jwtToken, "Content-Type": 'application/json'
}
})
.then((response) => {
try {
console.log("sports suceess then0--->");
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
console.log("sports suceess fileName--->", fileName);
ResponseUtil.callService(res, url);
res.send({});
}
catch (error) {
console.log("try catch error--->", error)
const errorMessage = error.response.data.message;
}
})
.catch((e) => {
console.log("e catch sports0--->", e);
console.log("e.message catch sports0--->", e.message);
console.log("catch sports--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
logs
sports suceess then0--->
sports suceess fileName---> ioreioreio=erierioerioerio
callService ===> /erpoperoperop/rejklerklkler
else if responseutil.jsURL ===> http://players/erpoperoperop/rejklerklkler
URL ===> http://players/erpoperoperop/rejklerklkler
express deprecated res.send(status, body): Use res.status(status).send(body) instead server\services\utils\ResponseUtil.js:56:30
(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:5548) [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.
There are a couple of issues with this implementation. The first issue is that you've neglected to return your promises so that they are applied to the promise chain. If you do not return the promise, then errors will not propagate up the promise chain, which defeats the purpose of promises. The second issue is that you're attempting to send a response twice, once in ResponseUtil.callService(res, url) and another time directly after that (e.g. res.send({});).
The console errors point out both of these mistakes:
1) Failure to chain the promises
(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
2) Duplicate call to res.send
express deprecated res.send(status, body): Use res.status(status).send(body) instead server\services\utils\ResponseUtil.js:56:30
I'm going to make the assumption that ResponseUtil.callService(res, url) returns a promise to answer this question since it appears that is the case.
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId,
password: credentials.auth.password
}
}).then((jwtResponse) => {
// Return the promise from get so it is applied to the promise chain
return axios.get(formatUrl, {
headers: {
"Authorization": `Bearer ${jwtResponse.data.jwt}`,
"Content-Type": 'application/json'
}
}).then((response) => {
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
// Return the promise from call service so it is applied to the promise chain
return ResponseUtil.callService(res, url);
});
}).catch((e) => {
// Catch any error that occurred in the promise chain...
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
return res.status(500).send(e.message || 'Something wrong');
});

UnhandledPromiseRejectionWarning when using a SoapClient

I am new in node.js, and I am experimenting things recently. A few days ago, I have tried to send a XML request to an API, with the use of easysoap-request. It worked perfectly, but I would have had to create an XML file for each different query, so I tried with easysoap. I found myself stuck pretty quickly, but I managed to resolve some issues with the help of this website. Now my program give an error that I have trouble understanding. Here my code first:
const EasySoap = require('easysoap');
const request = (async () => {
const params = {
host : 'https://someapi.com',
path : '/dir/soap',
wsdl : '/dir/wsdl',
headers: [{
'user-agent': 'Request-Promise',
'Content-Type': 'text/xml',
}]
}
var soapClient = EasySoap(params);
soapClient.call({
method :'one_methode',
attributes: {
xmlns: 'https://someapi.com'
},
params: {
'api' : {
'authentication' : {
'login' : 'mylogin',
'password' : 'mypassword'
},
'params' : {
'another_params' : {
'name' : 'Brian',
}
}
}
}
}).then((callResponse) => {
console.log(callResponse.data); // response data as json
console.log(callResponse.body); // response body
console.log(callResponse.header); //response header
}).catch((err) => {
throw new Error(err);
});
});
request();
And the error it give me:
node:10264) UnhandledPromiseRejectionWarning: Error: Error: no wsdl/xml response at soapClient.call.then.catch (C:\Users\user\Documents\src\script.js:40:15) at process._tickCallback (internal/process/next_tick.js:68:7) (node:10264) 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:10264) [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.
Is this a problem with the .catch() ? Can someone explain me ? Thanks
It's because you're throwing error inside catch, which is wrapped to Promise.reject since it's thrown inside async function, and not catching anywhere.
...
}).catch((err) => {
throw new Error(err);
});
You can either handle the error in that block like console.error(err)
or handle in your request() function call like
// request returns promise since you wrapped it in async function
request()
.catch(err => console.error(err))

Categories

Resources