try catch inside axios in then method in node js - javascript

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');
});

Related

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);
}
);
}
});

Dropbox's `filesGetTemporaryLink` throws an uncatchable `UnhandledPromiseRejectionWarning` and terminates Node.js

To get a download link to the file hosted on Dropbox, I'm using a Dropbox JavaScript API (7.0.0):
export const fileDownload = async function fileDownload(fileUUID) {
let isSucceeded;
let message;
let file;
const dbx = _dropboxFactory();
try {
const operationResult = await dbx.filesGetTemporaryLink({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
if ("OK" === http.STATUS_CODES[operationResult.status].toUpperCase()) {
file = Object.freeze({
length: operationResult?.result?.metadata?.size,
link: operationResult?.result?.link,
mime: mime.lookup(operationResult?.result?.metadata?.name),
name: operationResult?.result?.metadata?.name
});
isSucceeded = true;
message = SYS_MESSAGES.storageFileDownloadSucceeded.code;
} else {
isSucceeded = false;
message = SYS_MESSAGES.storageFileDownloadFailed.code;
}
} catch (err) {
file = "error";
isSucceeded = false;
message = "FIL_NOT_FOUND";
}
const downloadResult = Object.freeze({
file,
isSucceeded,
message
});
return downloadResult;
};
The problem is that when the path to the file is wrong, I get a Node.js exception:
(node:9156) UnhandledPromiseRejectionWarning: #<Object>
(node:9156) 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: 2)
(node:9156) [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've tested several options and came to conclusion that the issue is in:
const operationResult = await dbx.filesGetTemporaryLink({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
My questions:
Why does Node.js claim «unhandled promise rejection» or «promise which was not handled with .catch()» and throws an UnhandledPromiseRejectionWarning exception if the code, which generates it is wrapped by try-catch?
Starting Node.js 15.x.x, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. Therefore, how to avoid UnhandledPromiseRejectionWarning?
A temporal workaround:
To run Node.js with a flag --unhandled-rejections=warn.
This will prevent the termination of the Node.js process with a non-zero exit code upon UnhandledPromiseRejectionWarning.
The problem was in the Dropbox library and has been solved by the Dropbox team with the release of 7.1.0. After upgrading the code in the question works correctly.
try changing your fileResponse function to something like this. You are mixing up async/await with .then().catch() style syntax.
Just wrap your function in a try-catch
async function getDocument() {
try {
const response = await fetch(`${http() + ip}/downloadDocument`, {
body: JSON.stringify({fileUUID: oModel.oData[0].documentFile}),
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
method: "POST",
mode: "cors"
});
const data = await response.json();
return data;
} catch(err) {
console.log(err);
}
}

How to solve UnhandledPromiseRejectionWarning in NodeJS testing framework

I'm using custom commands in my testing framework based on Nightwatch.js. I want to do a PUT request via superagent. This os my custom command:
const superagent = require("superagent");
exports.command = function(url, header, body, callback) {
return superagent
.put(url)
.send(body) // sends a JSON post body
.set(header)
.then(result => {
callback(true, result);
return this;
})
.catch(err => {
if (err) {
callback(false, err);
return this;
}
});
};
And this command I'm using in my tests:
return client
.apiPut(apiUrl, header, body, function(status, result) {
assert.isTrue(status, "response status is false");
assert.isTrue(result.ok, "response result is NOT ok");
})
If everything is fine with the PUT request (status == true and successful response) then everything is fine and the test will finish, but if the PUT request is not successful (status != true and an error as result) I'm getting the following error message and the current Node process does not finish:
09:11:12 (node:103) UnhandledPromiseRejectionWarning: AssertionError: response status is false: expected false to be true
09:11:12 at /var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/pageobjects/MyPageView.js:59:20
09:11:12 at superagent.put.send.set.then.catch.err (/var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/commands/apiPut.js:14:9)
09:11:12 at <anonymous>
09:11:12 at process._tickCallback (internal/process/next_tick.js:189:7)
09:11:12 (node:103) 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)
09:11:12 (node:103) [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.
But I don't know what I'm doing wrong with the callback in my custom command. What should I do to solve that issue?
Thanks for the help. Now it is running. I've replaced the promise and replaced it completely with callbacks. Now it is working :)
const superagent = require("superagent");
exports.command = function(url, header, body, callback) {
return superagent
.put(url)
.send(body) // sends a JSON post body
.set(header)
.end((error, result) => {
if (error) {
callback(false, result, error);
} else {
callback(true, result, error);
}
});
};

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))

How to handle UnhandledPromiseRejectionWarning in fetch API

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.

Categories

Resources