Including the stack in custom errors


If you throw a custom error, it can be hard to track down where it came from if you're using a common function. In Reporting file, function and line number in Apps Script I showed how to get back an object with information about where you are, including stack information. Here's a simplified version to add stack information to your custom error messages.

To use

This is available in my cUseful library if you are using that. Otherwise you can just copy the code.

function tryit() {
  throw cUseful.errorStack('my custom error');
}

creates this

 Error:my custom error
at Code:250 (tryit)
at Code:247 (mystack)
 (line 250, file "Code"

The code

/**
 * get the stack
 * @return {string} the stack trace
 */
function errorStack(e) {
  try {
    // throw a fake error
    throw new Error();  //provoke an error
  }
  catch(err) {
    return 'Error:' + e + '\n' + err.stack.split('\n').slice(1).join('\n');
  }
}

The cUseful library

Many of the snippets in this section of the site are part of the cUseful library which you can include in your project. You can find the details below. 

https://script.google.com/macros/s/AKfycbwZ2Hht93wTNzvRmYINYF7obaOHciBXWcP_wAiEtyGq70_x3cI/exec?list=cUseful

The code for cUseful can also  be found on GitHub 

See  Google Apps Scripts snippets for more like this

For help and more information join our forumfollow the blogfollow me on twitter

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.




Comments