Search code examples
logginggoogle-apps-scriptstackdriver

Add line numb in apps script Console.error function


I'm using console.error() function to log errors for my sheets add-on made with apps script. E.g.:

 1   var a = null;
 2   a.toString();
 3   } catch(error) {
 4           console.error('Function_1(): ' + error); 
 5         }

However, my function is pretty big, and when I get some error like "can't use toString() on null", I'm not sure where the problem is.

I tried using it with throw:

1    var a = null;
2    a.toString();   
3    } catch(error) {
4           throw 'Function_1(): '+error; 
5          }

But then, I get the line number of throw: can't use toString() on null at line 4, while the problem is at line 2.

I looked at other threads, like: How do you pass back a custom error message from google apps scripts?

But well, it doesn't answer how to provide the correct line number.


Solution

  • If you inspect the Error object, error, received by your catch block, you can observe that it has several properties that can be accessed:

    try {
      ...
    } catch (error) {
      const parts = {};
      for (var i in error) {
        parts[i] = error[i];
      }
      console.error({message: "Apps Script error object decomposition", error: error, parts: parts});
    }
    

    An example Stackdriver log:

    enter image description here

    So you can include the full stack trace of your error in your logs, as well as the file and line number:

    try {
      ...
    } catch (e) {
      console.error({
        message: "An error occurred",
        errMsg: e.message,
        line: e.lineNumber,
        fileName: e.fileName,
        stackTrace: e.stack
      });
    
      if (<some conditions>) {
        // update message:
        e.message = "Unhandled error in so-and-so: " + e.message;
        // Re-raise with the same trace info by re-throwing it:
        throw e;
      }
    }