I’ve written a script that gets an image url from a cell in Google Sheets and adds that image to a template in Google Docs. However, when the cell is empty, the script crashes:
JavaScript
x
2
1
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
2
Really new to programming and would appreciate anyones help as to how to prevent the above code from crashing in the event a cell is empty
Advertisement
Answer
Usually there are two options:
- Check the value before:
JavaScript
1
9
1
if (row[14] != '') {
2
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
3
} else {
4
console.log('row[14] was empty');
5
var beforePhoto1 = 'default_value';
6
}
7
8
// rest code
9
- Try to use the value and skip any error with
try/catch
:
JavaScript
1
9
1
try {
2
var beforePhoto1 UrlFetchApp.fetch(row[14]).getBlob();
3
} catch(e) {
4
console.log('row[14] was empty');
5
var var beforePhoto1 = 'default_value';
6
}
7
8
// rest code
9