JavaScript: Catch errors in async function and stop the rest of the function if there are any - javascript

EDIT: ANSWER BELOW
I'm making my first JavaScript project and decided to make a simple weather app. It fetches weather data of a city you put in from the openweathermap.org api and displays it in a table. I firstly made it using fetch() and .then. I then learned about async functions and the await keyword. After converting the script to an asynchronous function, I came across a problem. If the first city you enter isn't a real city (an error is catched while fetching the api), the warning message appears, BUT the table also appears because the rest of the function still executes.
So my question is: how can I stop the async function if any errors are catched?
Here's the website: https://lorenzo3117.github.io/weather-app/
Here's the code:
// Launch weather() function and catch any errors with the api request and display the warning message if there are any errors
function main() {
weather().catch(error => {
document.querySelector("#warningMessage").style.display = "block";
console.log(error);
});
}
// Main function
async function weather() {
// Take city from input and reset input field
var city = document.querySelector("#cityInput").value;
document.querySelector("#cityInput").value = "";
// Get api response and make it into a Json
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=<apiKey>&units=metric");
const jsonData = await apiResponse.json();
// Removes warning message
document.querySelector("#warningMessage").style.display = "none";
// Puts the Json into an array and launches createTable function
var arrayJson = [jsonData];
createTable(document.querySelector("#table"), arrayJson);
// Function to create the table
function createTable(table, data) {
// Makes the table visible
document.querySelector("#table").style.display = "block";
// Goes through the array and makes the rows for the table
for (let i = 0; i < data.length; i++) {
let rowData = data[i];
var row = table.insertRow(table.rows.length);
// This var exists to make the first letter capitalized without making a gigantic line (see insertCell(3), line 53)
// Could be made into a function if needed
var weatherDescription = rowData.weather[0].description;
// Take latitude and longitude for google maps link
var lat = rowData.coord.lat;
var long = rowData.coord.lon;
// Make an a-tag for link to google maps
var mapLink = document.createElement("a");
mapLink.innerHTML = "Link";
mapLink.target = "_blank";
mapLink.href = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + long;
// Making rows in table
row.insertCell(0).innerHTML = rowData.name + ", " + rowData.sys.country;
row.insertCell(1).innerHTML = rowData.main.temp + " °C";
row.insertCell(2).innerHTML = rowData.main.humidity + "%";
row.insertCell(3).innerHTML = weatherDescription.charAt(0).toUpperCase() + weatherDescription.slice(1);
row.insertCell(4).appendChild(mapLink); // appendChild for anchor tag because innerHTML only works with text
}
}
And the repo: https://github.com/lorenzo3117/weather-app
Thank you

you can do this :
async function weather() {
try {
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=02587cc48685af80ea225c1601e4f792&units=metric");
} catch(err) {
alert(err); // TypeError: failed to fetch
return;
}
}
weather();

Actually, the error catched isn't an error with the api itself because the api still sends a json, but the error is catched while trying to read a certain object from the json (which doesn't exist because the json isn't a normal one with weather data). Therefore the function stops far later than expected, after the table was made visible.
I just put the line that made the table visible after the function that creates the table (after where the real error occurs). Also thanks #Dadboz for the try catch method which made the code even more compact. I also added an if else to check if the json file is the correct one so unnecessary code doesn't get executed. Thanks #James for pointing this out to me.
Here's the final code:
// Main function
async function weather() {
try {
// Take city from input and reset input field
var city = document.querySelector("#cityInput").value;
document.querySelector("#cityInput").value = "";
// Get api response and make it into a Json
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=<apiKey>&units=metric");
const jsonData = await apiResponse.json();
if (jsonData.message == "city not found") {
document.querySelector("#warningMessage").style.display = "block";
} else {
// Removes warning message
document.querySelector("#warningMessage").style.display = "none";
// Puts the Json into an array and launches updateTable function
var arrayJson = [jsonData];
updateTable(document.querySelector("#table"), arrayJson);
}
}
catch (error) {
console.log(error);
}
}
// Function to update the table
function updateTable(table, data) {
// Goes through the array and makes the rows for the table
for (let i = 0; i < data.length; i++) {
let rowData = data[i];
var row = table.insertRow(table.rows.length);
// This var exists to make the first letter capitalized without making a gigantic line (see insertCell(3), line 53)
// Could be made into a function if needed
var weatherDescription = rowData.weather[0].description;
// Take latitude and longitude for google maps link
var lat = rowData.coord.lat;
var long = rowData.coord.lon;
// Make an a-tag for link to google maps
var mapLink = document.createElement("a");
mapLink.innerHTML = "Link";
mapLink.target = "_blank";
mapLink.href = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + long;
// Making rows in table
row.insertCell(0).innerHTML = rowData.name + ", " + rowData.sys.country;
row.insertCell(1).innerHTML = rowData.main.temp + " °C";
row.insertCell(2).innerHTML = rowData.main.humidity + "%";
row.insertCell(3).innerHTML = weatherDescription.charAt(0).toUpperCase() + weatherDescription.slice(1);
row.insertCell(4).appendChild(mapLink); // appendChild for anchor tag because innerHTML only works with text
}
// Makes the table visible
document.querySelector("#table").style.display = "block";
}
Thanks everyone for your answers, have a good day!
Lorenzo

Related

update spreadsheet in serverside code run from client html javascript not working

I have an html where user requests add and enters data. The javascript in the body of the html calls the server side. I am unable to connect with the sheet either with saved ID or URL in order to add the row.
I cannot update of my spreadsheet despite #Serge insas comment that openById "it means "open for read and write". Am I making a simple mistake or is this impossible. The code initiated from the client side is running in the server.
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
Both get Error: Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
Gets error: Exception: Invalid argument: url
ABOVE IS THE IMPORTANT PART
/**
* this code is run from the javascript in the html dialog
*/
function addMbrCode(myAddForm) {
// removed logging
console.log("Beginning addMbrCode" );
paragraph = body.appendParagraph('Beginning addMbrCode.');
// Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
// const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
// var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
// var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
// Exception: Invalid argument: url
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
myAddForm = [ fName, lName, inEmail, fallNum, winNum, sprNum];
var fName = myAddForm[0];
var lName = myAddForm[1];
var inEmail = myAddForm[2];
var fallNum = myAddForm[3];
var winNum = myAddForm[4];
var sprNum = myAddForm[5];
var retCd = '';
/**
* 10 - successful add
* 20 - duplicate - not added
*/
var combNameRng = sheet.getRange(2, 4, numRows).getValues();
var inCName = (fName + '.' + lName).toString().toLowerCase();
if (combNameRng.indexOf(inCName) > 0 ) {
console.log("Alert: Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20 );
paragraph = body.appendParagraph("Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20);
retCd = 20;
return retCd;
}
sheet.appendRow([fName.toString().toLowerCase()
, lName.toString().toLowerCase()
,
, inEmail.toString().toLowerCase()
]);
const currRow = sheet.getLastRow().toString();
);
retCd = 10;
return retCd;
}
If this makes a difference, here is the javascript from the body of my html in the dialog window.
<script>
document.querySelector("#myAddForm").addEventListener("submit",
function(e)
{
alert('begin addEventListener');
e.preventDefault(); //stop form from submitting
var retCd = google.script.run.addMbrCode(this); // client side validation
document.getElementById('errMsg').textContent = 'Successful member
return false; // do not submit - redisplay html
}
);
</script>
Removed unneeded coding detail
Per #iansedano I created an object/array to use instead of this and added the successhandler and failurehandler. In either case I want to see the html again with my message. This is the current script. Response is so doggy I am not seeing alerts, Logger.log, or console.log. Crazy shoppers using my internet!
<script>
document.querySelector("#myRmvForm").addEventListener("submit",
function(e)
// removed alerts and logging
// removed client side validation for simplicity
cSideValidate();
// Then we prevent the form from being submitted by canceling the event
event.preventDefault();
});
function cSideValidate() {
dataObj = [
document.getElementById('fName').value,
document.getElementById('lName').value,
document.getElementById('email').value
];
var retCd = google.script.run.withSuccessHandler(serverReply)
.withFailureHandler(serverReply)
.rmvMbrCode(dataObj); // server side validation
}
function serverReply {
// logic to set the correct message - this is an example
document.getElementById('errMsg').textContent
= 'Successful delete using email.';
}
</script>
Nothing is being added to my spreadsheet so the server side code is not working. I see my loggin so I know it is getting there.
You're getting ssId from the script properties and assigning it to the ssId variable, but then you pass a string ("ssId") to the openById() function, not the value of the variable.
Try the following please:
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById(ssId).getSheetByName('Sheet1');

JavaScript Class Objects not returning value

I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!

Excel Javascript API fetch position of multiple sheets

How can I get the position of two worksheets using the Excel Javascript API?
Here is how it works just for one sheet:
Excel.run(function (ctx) {
var wSheetName = 'Sheet1';
var worksheet = ctx.workbook.worksheets.getItem(wSheetName);
worksheet.load('position')
return ctx.sync().then(function () {
console.log(worksheet.position);
});
});
=> it logs 0 to the console
But it doesn't logs anything if I try to get the position for two worksheets:
Excel.run(function (ctx) {
var wSheetName = 'Sheet1';
var wSheetName2 = 'Evars';
var worksheet = ctx.workbook.worksheets.getItem(wSheetName);
var worksheet2 = ctx.workbook.worksheets.getItem(wSheetName2);
worksheet.load('position')
worksheet2.load('position')
return ctx.sync().then(function () {
console.log(worksheet.position);
console.log(worksheet2.position);
});
});
I just tried your code, and it works fine. I wonder if you simply didn't have a sheet by one of those names, and so it was throwing an exception -- which was appearing to you as silent, since you didn't have a catch handler.
The code below, essentially the same as yours but with a catch statement, works correctly:
Excel.run(function(ctx) {
var wSheetName = 'Sheet1';
var wSheetName2 = 'Sheet2';
var worksheet = ctx.workbook.worksheets.getItem(wSheetName);
var worksheet2 = ctx.workbook.worksheets.getItem(wSheetName2);
worksheet.load('name, position')
worksheet2.load('name, position')
return ctx.sync().then(function () {
console.log(worksheet.name + ": " + worksheet.position);
console.log(worksheet2.name + ": " + worksheet2.position);
});
}).catch(function(error) {
OfficeHelpers.UI.notify(error);
OfficeHelpers.Utilities.log(error);
})
You can try this snippet live in literally five clicks in the new Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/Zlatkovsky/c61594f1c86970e8dba91fe94b7ca4b6. See more info about importing snippets to Script Lab.
Found the solution here ... maybe this will help someone
Excel.run(function (ctx) {
var worksheets = ctx.workbook.worksheets;
worksheets.load('items');
return ctx.sync().then(function () {
for (var i = 0; i < worksheets.items.length; i++) {
var sheet_name = worksheets.items[i].name;
var sheet_position = worksheets.items[i].position;
}
});

Unable to update table in Advanced Data Persistence mode

I have an issue related to database. I am currently working with Gupshup bot programming. There are two different data persistence modes which can be read here and here. In the advanced data persistence, the following code is documented to put data into data base:
function MessageHandler(context, event) {
if(event.message=='update bug - 1452') {
jiraUpdate(context);
}
}
function jiraUpdate(context){
//connect to Jira and check for latest update and values
if(true){
context.simpledb.doPut("1452" ,"{\"status\":\"QA pending\",\"lastUpdated\":\"06\/05\/2016\",\"userName\":\"John\",\"comment\":\"Dependent on builds team to provide right build\"}");
} else{
context.sendResponse('No new updates');
}
}
function DbPutHandler(context, event) {
context.sendResponse("New update in the bug, type in the bug id to see the update");
}
If I want to change only one of column (say status or last Updated) in the table for the row with key value 1452, I am unable to do that. How can that be done?
I used the following code:
function MessageHandler(context, event) {
// var nlpToken = "xxxxxxxxxxxxxxxxxxxxxxx";//Your API.ai token
// context.sendResponse(JSON.stringify(event));
if(event.message=='deposit') {
context.sendResponse("Enter the amount to be deposited");
}
if(event.message=="1000") {
jiraUpdate(context);
}
if(event.message== "show"){
context.simpledb.doGet("1452");
}
}
function HttpResponseHandler(context, event) {
var dateJson = JSON.parse(event.getresp);
var date = dateJson.date;
context.sendResponse("Today's date is : "+date+":-)");
}
function jiraUpdate(context){
//connect to Jira and check for latest update and values
if(true){
context.simpledb.doPut("aaa" ,"{\"account_number\":\"90400\",\"balance\":\"5800\"}");
} else{
context.sendResponse('No new updates');
}
}
/** Functions declared below are required **/
function EventHandler(context, event) {
if (!context.simpledb.botleveldata.numinstance)
context.simpledb.botleveldata.numinstance = 0;
numinstances = parseInt(context.simpledb.botleveldata.numinstance) + 1;
context.simpledb.botleveldata.numinstance = numinstances;
context.sendResponse("Thanks for adding me. You are:" + numinstances);
}
function DbGetHandler(context, event) {
var bugObj = JSON.parse(event.dbval);
var bal = bugObj.balance;
var acc = bugObj.account_number;
context.sendResponse(bal);
var a = parseInt (bal,10);
var b = a +1000;
var num = b.toString();
context.simpledb.doPut.aaa.balance = num;
}
function DbPutHandler(context, event) {
context.sendResponse("testdbput keyword was last put by:" + event.dbval);
}
Since the hosted DB that is provided by Gupshup is the DynamoDB of AWS. Hence you can enter something as a key, value pair.
Hence you will have to set the right key while using doPut method to store data into the database and use the same key to get the data from the database using the doGet method.
To update the data you should first call doGet method and then update the JSON with right data and then call doPut method to update the database with the latest data.
I have also added something which is not present in the documentation, You can now make DB calls and choose which function the response goes to.
I am refactoring your example as using 3 keywords and hard coding few things just for example -
have - this will update the database with these values
{"account_number":"90400","balance":"5800"}
deposit - on this, the code will add 1000 to the balance
show - on this, the code show the balance to the user.
Code -
function MessageHandler(context, event) {
if(event.message=='have') {
var data = {"account_number":"90400","balance":"5800"};
context.simpledb.doPut(event.sender,JSON.stringify(data),insertData); //using event.sender to keep the key unique
return;
}
if(event.message=="deposit") {
context.simpledb.doGet(event.sender, updateData);
return;
}
if(event.message== "show"){
context.simpledb.doGet(event.sender);
return;
}
}
function insertData(context){
context.sendResponse("I have your data now. To update just say \"deposit\"");
}
function updateData(context,event){
var bugObj = JSON.parse(event.dbval);
var bal = bugObj.balance;
var a = parseInt(bal,10);
var b = a + 1000;
var num = b.toString();
bugObj.balance = num;
context.simpledb.doPut(event.sender,bugObj);
}
function EventHandler(context, event) {
if (!context.simpledb.botleveldata.numinstance)
context.simpledb.botleveldata.numinstance = 0;
numinstances = parseInt(context.simpledb.botleveldata.numinstance) + 1;
context.simpledb.botleveldata.numinstance = numinstances;
context.sendResponse("Thanks for adding me. You are:" + numinstances);
}
function DbGetHandler(context, event) {
var accountObj = JSON.parse(event.dbval);
context.sendResponse(accountObj);
}
function DbPutHandler(context, event) {
context.sendResponse("I have updated your data. Just say \"show\" to view the data.");
}

Are there promises on Google Apps Script?

I have a form that my users enter data and I use onFormSubmit to trigger a script that creates a CSV based on the data inserted and after I create the CSV file I delete the data. Problem is that I am deleting the data before creating CSV file. Usually I would just make a promise call but I think it is not possible with Google Apps Script. Is there any alternative to it?
So my complete code is here:
More insight about what it does:
When I receive a new form entry, the "Avaliacao" sheet gets updated and will trigger testTrigger().
Then, it will write the email and the usercity in the LastUser city so it can lookup for some data that I will use to build my CSV file. But the saveAsCsv function is called before the sheet completed its VLOOKUP calls. So my CSV file is empty.
Another issue that I have with synchronization is that if I enable the sLastUser.clear(); line it will also delete before creating the CSV.
function testTrigger () {
//open the sheets
var SS = SpreadsheetApp.getActiveSpreadsheet();
var sAvaliacao = SS.getSheetByName("Avaliação");
var sPreCSV = SS.getSheetByName("PreCSV");
var sInput = SS.getSheetByName("Input");
var sLastUser = SS.getSheetByName("LastUser");
var dAvaliacao = sAvaliacao.getDataRange().getValues();
var dInput = sInput.getDataRange().getValues();
var avaliacaoLastRow = sAvaliacao.getLastRow()-1;
var userEmail = dAvaliacao[avaliacaoLastRow][2];
var userCity = dAvaliacao[avaliacaoLastRow][5];
var userId = dInput[3][52];
sLastUser.appendRow([userEmail, userCity]);
saveAsCSV(userId);
// sLastUser.clear(); <== this is the line where I can`t enable
}
function saveAsCSV(csvName) {
// Name
var fileName = String(csvName) + ".csv"
// Calls convertcsv
var csvFile = convertOutputToCsv_(fileName);
// create the file on my drive
DriveApp.createFile(fileName, csvFile);
}
function convertOutputToCsv_(csvFileName) {
// open sheets
var sPreCSV = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PreCSV");
var cont = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Input").getDataRange().getValues()[3][50] + 1;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PreCSV").getRange(1, 1, cont, 3);
try {
var data = ws.getValues();
var csvFile = undefined;
// Loop through the data in the range and build a string with the CSV data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// Join each row's columns
// Add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
Now with engine v8 Promise is defined object
Indeed, the JS engine used by Google Apps Script does not support promises (Logger.log(Promise); shows it's undefined).
To make sure that spreadsheet changes take effect before proceeding further, you can use SpreadsheetApp.flush().
Another relevant feature is event object passed by the trigger on Form Submit: it delivers the submitted data to the script without it having to fish it out of the spreadsheet.
There are no native Promises in GAS. With that said you can write your code in ES6/ESnext and make use of promises that way. To see how you can configure modules to expose the to the global scope see my comment here.
By doing this you can take advantage of promises. With that said depending on the size of your project this may be overkill. In such a case I'd advise using simple callbacks if possible.

Categories