0

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.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Sam Tyurenkov
  • 430
  • 4
  • 19

2 Answers2

4

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;
  }
}
tehhowch
  • 9,645
  • 4
  • 24
  • 42
2

Use e.lineNumber where e is an Error object instance. Example:

function myFunction() {
  try {
    throw new Error('Error message');
  } catch(e) {
    console.error(e.lineNumber)
  }
}

NOTE: Instead of e you could use error or any other variable name that fits your coding style.

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • e.lineNumber is null in Json Payload. but it worked with e.stack, as @tehhowch suggested. – Sam Tyurenkov Mar 04 '19 at 22:39
  • Have you tried the function on my answer? It works pretty fine for me. Anyway I added a Q/A related to the json payload "issue". – Rubén Mar 04 '19 at 23:21