Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

how to use if inside while loop

Priya75
Tera Contributor

Hi All,

 

My code is just updating the else condition if the value is matched. i want to give the error message as well.


var server = request.split(',');
for (var i = 0; i < server.length; i++)

{
var gr = new GlideRecord("u_server_details");
gr.addQuery("u_server_name.name", server[i].trim());
gr.query();
while (gr.next()) {
if (!gr.next()){
response.setStatus(400);
respObj.body = {
"message": "server details are not updated",
"detail": "faliure",
};
}
else{
response.setStatus(200);
gr.patch_date = requestTime;
gr.update();



respObj.body = {
"message": "Server Details are updated",
"detail": "Success",
};
}

 



}
}

1 ACCEPTED SOLUTION

@Priya75 

next question

do you want to show error message containing the name of servers not found in table?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

11 REPLIES 11

@Priya75 

next question

do you want to show error message containing the name of servers not found in table?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

yes

@Priya75 

something like this and enhance it further

var notFoundServers = [];
var foundServers = [];
for (var i = 0; i < server.length; i++)
{
	var gr = new GlideRecord("u_server_details");
	gr.addQuery("u_server_name.name", server[i].trim());
	gr.setLimit(1);
	gr.query();
	if (!gr.next()){
		notFoundServers.push(server[i].trim().toString());
	}
	else{
		gr.next();
		gr.patch_date = requestTime;
		gr.update();
		foundServers.push(server[i].trim().toString());
	}
}

if(failedServers.length > 0){
	response.setStatus(200);
	respObj.body = {
		"message": "Server Details are updated for " + foundServers.toString(),
		"detail": "Success",
	};
}
else{
	response.setStatus(400);
	respObj.body = {
		"message": "server details are not updated for " + notFoundServers.toString(),
		"detail": "faliure",
	};
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Could you explain why are you using

if(failedServers.length > 0

I want to give error, even if one server is not updated. 

this shows 200 status for invalid servers also.