How do you pass back a custom error message from google apps scripts?

Solution 1:

As with any javascript, you can use:

try {
  ...
}
catch (error) {
  throw new Error( "More meaningful error." );
}

There are [numerous examples][1] of this in use, even if the questions aren't exactly yours.

My personal opinion is that it's best if you check the input to your function and throw errors on that (like [this answer][2]), rather than catching the errors from service calls. An appropriate time to use try..catch would be when you have no practical way to validate parameters, as in [this answer][3].


  [1]: https://stackoverflow.com/search?q=%5Bgoogle-apps-script%5D+throw+catch
  [2]: https://stackoverflow.com/a/17092883/1677912
  [3]: https://stackoverflow.com/a/16796169/1677912

Solution 2:

Here is the best way to pass data from your script into your error message. First setup a global variable object to store your data that you need for the error handling. Then store data to this object in each function's try{} section. Finally in catch(e) call an errHandler function that will pass the error data object. See the following code: code.gs.

var onErrObj = {}
function myFunction(){

 try{
  // function code goes here;
  // add more elements to onErrObj as desired;
 }catch(e){
      onErrObj['data1'] = 'someData';
      onErrObj['data'] = 'some Other Data';
      errHandler(e,'myFunction');
 }

 function errHandler(e,strFunc){
      var message = e.message+'\n in file: '+e.fileName+' on line: '+e.lineNumber;
      var sendto = '[email protected]';
      var subject = 'My App encountered an error occured in '+strFunc;
      var errProps = JSON.stringify(this.onError);
      message = subject+'\n'+message+'\n onError: '+errProps;
      GmailApp.sendEmail(sendto, subject, message); 
}