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.

For more like this see Google Apps Scripts Snippets
For help and more information join our forum, follow the blog, follow me on twitter