Search code examples
google-classroom

Catching Errors with Google Classroom API


What's the right way to catch errors using the Google Classroom API?

I'm trying to do something like:

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

But if a Google user who doesn't have a Classroom account executes this code, it throws an error, and I'm unclear on how to catch/handle it.

I've tried wrapping this block of code with a try {...} catch(error) {...} and that doesn't catch it. I've also tried adding a .catch(function(error){ ... }); after then .then() statement and that also doesn't seem to work.


Solution

  • The answer is here: https://developers.google.com/api-client-library/javascript/features/promises

    The .then call takes two arguments. The first is a function invoked on success, and the second is a function invoked on failure:

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