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

后端 未结 3 1614
甜味超标
甜味超标 2020-12-16 13:15

When running a google apps script from a google spreadsheet, if one of the google apis is used incorrectly a red \"butterbar\" error is shown at the top of the spreadsheet.

3条回答
  •  死守一世寂寞
    2020-12-16 13:35

    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 = 'yourname@youremail.com';
          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); 
    }
    

提交回复
热议问题