I have this function which is a search query. This works fine unless the query string name is not detailed enough which then throws up an error message
request( url, function (error, data) {
errorText = arguments['0'];
if (error) {
callback('Unable to connect to location services!', undefined)
} else if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
}
else {
callback( {
data = data.body,
namePlace: data.suggestions[1].entities[0].name,
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
})
The error message from the console is
namePlace: data.suggestions[1].entities[0].name,
^
TypeError: Cannot read property 'name' of undefined
I want to be able to capture this error message and callback 'Unable to find location, try another search.'
It sounds like what you want to check for is whether data.suggestions[1].entities has any entries. Perhaps something like:
else if (data.suggestions[1].entities.length === 0) {
callback('Unable to find location, try another search.', undefined)
}
Depending on how reliable the resulting data structure is, you might also check for null or undefined values. But for this particular error it looks like entities is defined and an array but just has no entries.
You need to change the logical order of the first if, otherwise else if (error) will prevent if (errorText.includes('Cannot read property')).
Have you previously defined let request = new Request(<uri>)?
What is it that you're trying to do?
request( url, function (error, data) {
errorText = arguments['0']; // What are you trying to do here?
if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
} else if (error) {
callback('Unable to connect to location services!', undefined)
} else {
callback( {
data = data.body, // What are you trying to do here?
namePlace: data.suggestions[1].entities[0].name, // What are you trying to do here?
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
}); // <- semicolon here
Related
I have an async function inside an if/else statement. I just want to check whether there is a file in the request body before even using it otherwise it throws an error. Why is this happening? And is there anything better I could do to handle the problem ?
//save image to cloudinary
if (typeof(banner) !== undefined) {
//this piece of code is always executing even if the image is not present in request or is undefined
cloudinary.uploader.upload(banner,
async function(error, result) {
if (error) {
return res.status(409).send("Something went wrong while uploading image")
console.log(error)
}
article.banner = result.url
const savedArticle = await article.save()
return res.status(201).send(JSON.stringify({
redirect_uri: "/articles/" + savedArticle.slug
}))
})
} else {
return res.status(400).send("Missing file")
}
Your outer if does nothing, because typeof banner will never be the value undefined (it could be the string "undefined" though).
typeof returns a string with the type name in it, so if (typeof banner !== 'undefined') should work.
However, most likely you don't even need typeof here - if (banner !== undefined) or even just if (banner) should work too in your case.
So basically I have a similar block written in Express:
var sqlite3 = require('sqlite3');
const data = {};
const db = new sqlite3.Database("sqlite/test.db");
db.run("INSERT INTO [Employees]([Name]) VALUES(?)", [name], function (err) {
if (err) { //this is the error block
data.error = err.code;
data.status = 0;
}
else { //this is the success block
data.data = { Name: name, Id: this.lastID };
data.status = 1;
}
db.close();
res.send(data);
});
This does what it looks like, just a simple insert statement and its callback. The update, select and delete operations are literally all the same.
But whenever I get errors (syntax error, missing fields, missing tables, yada yada), I always just get {errNo: 0, code: "SQLITE_ERROR"} in my err argument, which is annoyingly unspecific and unhelpful.
Is there a way to fix the error handling and make it not insanity inducing?
This is the closest thing I found to documentation on the error object. You probably want to look at err.message.
Sorry for the Noob Question. I'm trying to write a node.js function called "getTransitionId" that uses the jira-connector plugin to retrieve data for possible transitions for a particular issue.
The getTransitions function from the jira-connector takes two parameters: an object with the parameters of the ticket, and a function to execute once the call is finished.
Here's my problem: for reasons beyond the scope of this question, I want to access this data outside the function that's being passed as parameter to "getTransitions." But I can't figure out how. I understand that the last return statement (return "transitionData") is returning "undefined" because it's executing a return statement before the call is finished, but I don't know how to fix that.
Can I correctly use a callback in this case? If so, how would I use it in a function that is being passed as a parameter to another function?
const JiraApi = require('jira-connector');
const jira = new JiraApi( {
host: //Jira URL
basic_auth: {
//Authentication Information
}
});
function getTransitionId (ticketNumber, transition) {
jira.issue.getTransitions({
issueKey: ticketNumber,
}, function(error, transitions){
const transitionData = transitions['transitions'];
});
return transitionData;
}
Thanks for the help. Hope this made sense.
You could make your own getTransitionId function take a callback function as an argument. Here's an incomplete example (see ahead):
function getTransitionId (ticketNumber, transition, callback) {
jira.issue.getTransitions({
issueKey: ticketNumber,
}, function(error, transitions){
const transitionData = transitions['transitions'];
const id = /* ..get ID fron transitionData, somehow.. */
callback(id);
});
}
// Called like this:
getTransitionId(ticketNumber, transition, function(id) {
console.log("Got the ID:", id);
});
This isn't perfect, though. What if getTransitions has an error?
When you call jira.issue.getTransitions, you pass a callback function which takes two parameters: error and transitions. This is standard for functions which take callbacks in JavaScript - that is, callbacks usually take an error parameter (null or undefined if there was no error) and a data parameter (containing results of the action, like fetched transitions or an id).
We can change getTransitionId to take an error and then pass the error to the callback that you gave to getTransitionId:
function getTransitionId (ticketNumber, transition, callback) {
jira.issue.getTransitions({
issueKey: ticketNumber,
}, function(error, transitions){
if (error) {
callback(error);
return;
}
const transitionData = transitions['transitions'];
const id = /* ..get ID fron transitionData, somehow.. */
callback(null, id);
});
}
(Note that we use a return; statement inside if (error) -- that's so that we don't continue and try to use the transitions argument, which is probably undefined, since there was an error in jira.issue.getTransitions. This also prevents callback from being called a second time.)
Since we've added an error argument, we need to change how we call getTransitionId:
getTransitionId(ticketNumber, transition, function(error, id) {
if (error) {
console.error("There was an error fetching the transition ID:", error);
return;
}
console.log("Got the ID:", id);
}
(Since we do callback(null, id); in the code for getTransitionId, error will be null, so the code in if (error) { won't run. Of course, if there is an error, if (error) { will be run, and that's what we want!)
By adding code to handle errors passed to your callbacks, you make your code safer. Contrastingly, if you ignore error, you might end up having errors in your code that are hard to find - for example, you might have a TypeError because transitions is undefined, or see "Got the ID: undefined" in the log!
I have code that attempts to access a database and search it for a specific field. The database itself is not exactly accessible by me; I can only pull certain information from it. In the following code, when the field exists, the code returns the respective user info. When it does not exist, it skips the code and returns absolutely nothing. How can I make my code know that the code was skipped and it isn't just a latency compensation problem. I was trying to make the code return null or undefined and then check for that in a variable, but I'm not sure how to do that. This code is on the server side:
client.search(base, options, function (err, res) {
if (err) {
console.log('search error:' + err);
}
res.on('searchEntry', function (entry) {
if (JSON.stringify(entry.object, null, 2) === undefined) {
userData = null;
}
else {
userData = JSON.stringify(entry.object, null, 2);
}
});
});
I'm trying to manipulate the data that is sent back to the client via Deepstream with the new dataTransforms API, however, I always get Uncaught SyntaxError: Unexpected end of input in the console. It might be that it takes too long to make the database lookup for Deepstream but I'm not quite sure.
My relevant code is:
DSServer.set('dataTransforms', [
{
topic: DSServer.constants.TOPIC.RECORD,
action: DSServer.constants.ACTIONS.READ,
transform: transformRecord
}
]);
var transformRecord = function (data, metadata) {
if (metadata.recordName.split('/')[0] === 'team') {
var new_member_info = [];
var i = 0;
_.forEach(data.members, function (members) {
r.table('user').get(members.user_id).run()
.then(function (doc) {
if (doc !== null) {
new_member_info.push({
user_id: members.user_id,
display_name: doc._d.display_name,
username: doc._d.username
});
i += 1;
if (i === data.members.length) {
data.members = new_member_info;
return data;
}
}
})
.error(function (err) {
console.error(err);
});
});
} else {
return data;
}
};
Whenever there is READ from a RECORD it will check if it's a read from the team record. If it is a read from the team-record it will fetch all members that are a part of that team and add it to members: {}.
When it has iterated over all members and added the information about them it will return the new data.
So, any idea what might be wrong?
Am I understanding the dataTransforms wrong?
For performance reasons, all data-transforms are expected to return a result synchronously.
r.table('user').get(members.user_id).run()
.then(...
however runs asynchronously and returns its value to the function used in then, rather than the dataTransform function. It's also crucial to always return the data, whether transformations were applied or not.
If I understand it correctly, your usecase is to load information for a number of users from a RethinkDb server. Might I recommend either using a list of recordnames for this usecase or build a data provider to interact with RethinkDb.