My previous question was really bad written (sorry for that!) so I'll try to do it right this time. I'm using NodeJS and I wrote the following code:
const car_reporter = {
// Some Code here (Removed to make it clear)
httpClient : null,
scriptReport: function(username, options) { // Some code here (Removed to make it clear)
},
APIReport: function(username, options) {
if (!(this.httpClient)) {
this.init();
}
try {
if ('car' in options) {
var reqConfig = {
method: 'post',
url: '/car',
headers: {
'content-type': 'application/json',
},
data: {
'carName': carName, // global
'username': username,
'car': options.car
}
};
this.httpClient(reqConfig).catch(function (error) {
throw new Error('Error while posting car\n' + error);
});
}
// OTHER CODE HERE - NOTICE ME :) (Removed to make it clear)
} catch (e) {
return e;
}
},
report: function (username, options) {
if (username === null) {
return new Error('Invalid username');
}
if (fs.existsSync(this.script_path)) {
return this.scriptReport(username, options);
} else {
return this.APIReport(username, options);
}
},
init: function() {
this.httpClient = axios.create({
baseURL: this.api_url
});
}
};
module.exports = car_reporter;
The way I call it:
function report_car(user_id, car) {
var options = { car: car };
var result = car_reporter.report(user_id, options);
if (result instanceof Error) {
logger.error(result);
}
}
I want to throw Error
in APIReport
if the post failed. But it says: UnhandledPromiseRejectionWarning: Unhandled promise rejection
. What is the right way here to handle errors and return Error
if post request didn't work? I can't do return this.httpClient(...
because there is other code after that request. I might need add .then(...
but how do I know that the post failed?
from What is the right way to handle post request fail in NodeJS?
No comments:
Post a Comment