Skip to content

Node.js Error Handling

General error handling for the Node.js client libraries use standard JavaScript mechanisms. The client library methods are asynchronous and return promises. In the case of an error, the promise will pass an error to the catch handler if specified.

The standard way to handle errors in promise-based syntax looks like this:

MessagesClient.listMessages({
  parent: 'projects/-',
  startTime: { seconds: new Date().getTime() / 1000 },
  endTime: { seconds: new Date().getTime() / 1000 + 86400 }
}).then(response => {
  console.log('Message List', response);
}).catch(error => {
  console.error('Got an error', error)
});

In the case you are using async/await. The standard way to handle an error will look like this:

(async () => {
  try {
    let response = await MessagesClient.listMessages({
      parent: 'projects/-',
      startTime: { seconds: new Date().getTime() / 1000 },
      endTime: { seconds: new Date().getTime() / 1000 + 86400 }
    });

    console.log(response);
  } catch (error) {
    console.log(error);
  }
})();