使用 Google 课堂 API 捕捉错误

Catching Errors with Google Classroom API

使用 Google 课堂 API 捕获错误的正确方法是什么?

我正在尝试做类似的事情:

gapi.client.classroom.courses.list({
  pageSize: 100
}).then((response) => {
  return process(response);
});

但是如果 Google 没有课堂帐户的用户执行此代码,它会抛出错误,我不清楚如何 catch/handle 它。

我试过用 try {...} catch(error) {...} 包装这段代码,但没能捕捉到。我也试过在 .then() 语句之后添加 .catch(function(error){ ... });,但似乎也不起作用。

答案在这里: https://developers.google.com/api-client-library/javascript/features/promises

.then 调用有两个参数。第一个是成功时调用的函数,第二个是失败时调用的函数:

.then(
  function(response) {
    return process(response);
  },
  function(errorResponse) {
    return handleError(errorResponse);
  }
);