如何正确处理 Google App Script 中的 Google SDK 错误

How to properly handle Google SDK errors in Google App Script

我正在编写一个 google 网络应用程序,它经常使用 Admin Directory。但是我想知道应该如何处理错误,因为当对 api 的请求失败时我没有得到正确的错误对象。

示例:我想检查自定义架构是否存在,如果不存在,我想做其他事情:

 try{
   var resp =  AdminDirectory.Schemas.get("129898rgv", "someCustomSchema");
  }catch(err){
     // if schema does not exist do this
      schemaNotExistFunction();
      Logger.log(err);
   }

不幸的是,我什至没有从错误中得到 http status code。在 Google Apps 脚本中是否有另一种处理错误的方法?

而不是

Logger.log(error) 

使用

Logger.log('%s, %s',error.message, error.stack);

有关错误实例属性的完整列表,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

以上是因为Logger.log将参数解析为字符串。当你传递一个错误对象时 error.name 被记录,另一方面通过使用

例子

运行 使用新运行时 (V8) 的独立项目中的以下代码将记录几条消息。

function myFunction() {
  try{
    SpreadsheetApp.getUi();
  } catch (error) {
    Logger.log(error);
    Logger.log('%s, %s', error.message, error.stack);
  }
}

另一种方法是使用 console.log 而不是 Logger.log

function myFunction() {
  try{
    SpreadsheetApp.getUi();
  } catch (error) {
    console.log(error);
    console.log('%s, %s', error.message, error.stack);
  }
}