Throwing custom exceptions and error messages in Google Sheets custom function?
Asked Answered
E

4

11

In Google Sheets (as with Excel, etc) if a user enters bad input into a formula, an error code will be printed in the offending cell and a small pop-up provides more detail about the error. So if I enter =SQRT(-1), #NUM! is printed in the cell and the pop-up explains that the value needs to be equal to or greater than 0.

How can I replicate this with a custom function in Google Sheets? Throwing an exception mostly works. For example, if I catch an out-of-bounds input value and then throw a custom exception, #ERROR! is printed in the offending cell (which is fine) and the exception's accompanying string is printed in the corresponding pop-up (which is also fine). The problem is that the Google Apps Script engine also appends to the exception message the corresponding source code line that generated the exception. So instead of the pop-up simply reading "The input value must be between 0.0 and 1.0", it will read "The input value must be between 0.0 and 1.0 (line 199)".

Is there any way to suppress the printing of the line number, or to overwrite the pop-up's message? I want to be able to throw custom errors and provide detailed error messages for my users. But I don't want them to be confused by a reference to a line number that is irrelevant to them.

Encrimson answered 2/10, 2014 at 0:9 Comment(0)
P
8
if (some_condition)
{
  // will end execution with error    
  throw 'Error. My custom error description.';
}
Psychological answered 30/3, 2018 at 14:16 Comment(0)
R
3

This is a reported problem.

Visit Issue 4422, star it to vote and for updates.

Rancourt answered 2/6, 2015 at 18:13 Comment(0)
T
1

Just Adding to the comment above about the throw. This works nicely because in a google sheet it carries the inner emessage to the pop up.

if (!searchString || !list)
    throw "ERROR: NearMatchList requires 2 arguments.";

enter image description here

Tantalus answered 9/3, 2023 at 16:36 Comment(0)
V
0

Use try...catch and the message property of the error object, then return the error message instead of throwing an error. I.E.:

/**
 *
 * @customfunction
 */
function myDiv(dividend,divisor){
  var quotient;
  try{
     quotient = dividend / divisor;
  } catch(error) {
     quotient = error.message;
  } finally {
     return quotient;
  }

}

Reference

Virescence answered 14/6, 2020 at 0:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.