Reporting Errors

You can emit an error from a Cloud Function to Stackdriver Error Reporting by simply logging an Error object to the console on the error level:

console.error(new Error('message'));

You can view the reported errors in Stackdriver Error Reporting in the GCP Console. You can also see the errors reported from a particular function when you select it from the list of functions in the GCP Console.

Errors also appear in Stackdriver Error Reporting when your function produces an uncaught error, or if you explicitly throw an object of type Error. However, uncaught errors and exceptions force a cold start on future invocation. So for performance reasons, you should use the first approach (logging an Error object).

Note that the following will not emit a Stackdriver error:

  • Throwing something that is not an Error object: for example, throw 1;
  • Logging an error object on the info level: for example, console.info(new Error('message'));
  • Logging something that is not an Error object: for example, console.error('message');
  • Normal completion of your function with an error result: for example, callback('message'); for background functions, and res.status(500).send('message'); for HTTP functions.

When reporting errors in the catch block of a try-catch statement, or the catch callback of a Promise, the err object will often already be a typed Error object. If you are using Google services through a Google-provided library, you can simply log the provided err object directly:

Node.js

try {
  // Throw an Error object (to simulate a GCP API failure)
  throw new Error('Error object!');
} catch (err) {
  // err is already an Error object
  console.error(err);
}

If you are not sure whether the provided err is an Error object, you can check it as follows:

Node.js

try {
  // Throw an unknown error type
  if (someCondition) {
    throw 'Error string!';
  } else {
    throw new Error('Error object!');
  }
} catch (err) {
  // Determine the error type
  if (err instanceof Error) {
    console.error(err);
  } else {
    console.error(new Error(err));
  }
}

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation