Unhandled errors in production scripts are the worst — a trigger silently fails at 2 AM and nobody notices until Monday. Here's how to write Apps Script that handles failures gracefully, notifies you when things go wrong, and recovers automatically where possible.
Basic try/catch
functionriskyOperation(){try{const sheet =SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();const value = sheet.getRange('A1').getValue();// ... do something with valueLogger.log('Success: '+ value);}catch(error){Logger.log('Error: '+ error.message);Logger.log('Stack: '+ error.stack);}}
Get notified by email when a trigger fails
functionrunWithErrorAlert(fn, fnName){try{fn();}catch(error){const message =`Script: ${fnName}Error: ${error.message}Stack: ${error.stack}Time: ${newDate().toLocaleString()}`.trim();GmailApp.sendEmail(Session.getActiveUser().getEmail(),`⚠️ Apps Script Error: ${fnName}`, message
);Logger.log('Error alert sent: '+ error.message);throw error;// Re-throw so Apps Script also logs it}}// Wrap your main functionfunctionmyDailyJob(){runWithErrorAlert(()=>{// Your actual logic hereprocessData();},'myDailyJob');}
functionhandleSpecificErrors(){try{const file =DriveApp.getFileById('NONEXISTENT_ID');}catch(error){if(error.message.includes('No item with the given ID')){Logger.log('File not found — it may have been deleted.');}elseif(error.message.includes('Access denied')){Logger.log('Permission error — check sharing settings.');}else{throw error;// Unknown error — re-throw}}}
Set up Apps Script's built-in error notifications
Apps Script can email you automatically when a trigger-based execution fails:
Open the script editor.
Go to Triggers (clock icon in the left sidebar).
Edit your trigger.
Under Failure notification settings, choose your notification frequency.
This is a quick win — enable it for all production triggers.