Report errors

Automatically reporting errors

You can emit an error from a Cloud Function to Stackdriver Error Reporting as shown below:

Node.js

// These WILL be reported to Stackdriver Error Reporting
console.error(new Error('I failed you'));
throw new Error('I failed you'); // Will cause a cold start if not caught

// These will NOT be reported to Stackdriver Error Reporting
console.info(new Error('I failed you')); // Logging an Error object at the info level
console.error('I failed you'); // Logging something other than an Error object
throw 1; // Throwing something other than an Error object
callback('I failed you');
res.status(500).send('I failed you');

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

Uncaught exceptions produced by your function will appear in Stackdriver Error Reporting. Note that some uncaught exceptions, for example, those thrown asynchronously, may cause a cold start on a future function invocation. This reduces function performance.

If you are using Google services through a Google-provided library, you can log the provided error as shown below:

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);
}

Manually reporting errors

To report an error to Stackdriver Error Reporting from a function, use the Stackdriver Logging API.

Importing dependencies

From your functions directory, install the Google Stackdriver Logging Client Library for Node.js:

npm install --save @google-cloud/logging

Import the Google Cloud Client Library to access the Logging API:

const Logging = require('@google-cloud/logging');

// Instantiates a client
const logging = Logging();

Sending to Stackdriver

A properly formed log entry requires a MonitoredResource object and an ErrorEvent object.

This example reportError function demonstrates the minimum data required to report an error to Stackdriver Error Reporting.

function reportError(err, context = {}) {
  // This is the name of the StackDriver log stream that will receive the log
  // entry. This name can be any valid log stream name, but must contain "err"
  // in order for the error to be picked up by StackDriver Error Reporting.
  const logName = 'errors';
  const log = logging.log(logName);

  // https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
  const metadata = {
    resource: {
      type: 'cloud_function',
      labels: {function_name: process.env.FUNCTION_NAME},
    },
  };

  // https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent
  const errorEvent = {
    message: err.stack,
    serviceContext: {
      service: process.env.FUNCTION_NAME,
      resourceType: 'cloud_function',
    },
    context: context,
  };

  // Write the error log entry
  return new Promise((resolve, reject) => {
    log.write(log.entry(metadata, errorEvent), (error) => {
      if (error) {
       return reject(error);
      }
      return resolve();
    });
  });
}

The reportError function can be used to manually report errors:

// Charge the Stripe customer whenever an amount is written to the Realtime database
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}')
    .onCreate((snap, context) => {
      const val = snap.val();
      // Look up the Stripe customer id written in createStripeCustomer
      return admin.database().ref(`/stripe_customers/${context.params.userId}/customer_id`)
          .once('value').then((snapshot) => {
            return snapshot.val();
          }).then((customer) => {
            // Create a charge using the pushId as the idempotency key
            // protecting against double charges
            const amount = val.amount;
            const idempotencyKey = context.params.id;
            const charge = {amount, currency, customer};
            if (val.source !== null) {
              charge.source = val.source;
            }
            return stripe.charges.create(charge, {idempotency_key: idempotencyKey});
          }).then((response) => {
            // If the result is successful, write it back to the database
            return snap.ref.set(response);
          }).catch((error) => {
            // We want to capture errors and render them in a user-friendly way, while
            // still logging an exception with StackDriver
            return snap.ref.child('error').set(userFacingMessage(error));
          }).then(() => {
            return reportError(error, {user: context.params.userId});
          });
        });

You can pass user details through the ErrorContext parameter. The Stackdriver UI displays these details and uses them to calculate the number of affected users.

ErrorContext can also be passed information on an HTTP Request:

export.httpError = functions.https.onRequest((request, response) => {
  const error = new Error('Test error');
  const httpRequest = {
    method: request.method,
    url: request.originalUrl,
    userAgent: request.get('user-agent'),
    referrer: '',
    remoteIp: request.ip
  };
  reportError(error, {httpRequest}).then(() => {
    response.end();
  });
});

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.