获取我们在 Firebase 峰会上发布的所有信息,了解 Firebase 可如何帮助您加快应用开发速度并满怀信心地运行应用。了解详情

报告错误

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

自动报告错误

您可以从云函数向错误报告发出错误,如下所示:

节点.js

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

// These WILL be reported to Error Reporting
console.error(new Error('I failed you')); // Logging an Error object
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');

如果您想要更细粒度的错误报告,可以使用错误报告客户端库

您可以在 GCP Console 的错误报告中查看报告的错误。当您从 GCP Console的函数列表中选择某个特定函数时,您还可以查看该函数报告的错误。

您的函数产生的未捕获异常将出现在错误报告中。请注意,某些类型的未捕获异常(例如异步抛出的异常)将导致在将来的函数调用时发生冷启动。这会增加您的函数运行所需的时间。

手动报告错误

要从函数向错误报告报告错误,请使用Cloud Logging API。

导入依赖项

在您的functions目录中,安装适用于 Node.js 的 Cloud Logging 客户端库:

npm install --save @google-cloud/logging

导入并初始化 Cloud Logging 客户端库:

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

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

发送到 Cloud Logging

格式正确的日志条目需要MonitoredResource对象和ErrorEvent对象。

此示例reportError函数演示了向错误报告报告错误所需的最少数据。

function reportError(err, context = {}) {
  // This is the name of the 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 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();
    });
  });
}

reportError函数可用于手动报告错误:

exports.createStripePayment = functions.firestore
  .document('stripe_customers/{userId}/payments/{pushId}')
  .onCreate(async (snap, context) => {
    const { amount, currency, payment_method } = snap.data();
    try {
      // Look up the Stripe customer id.
      const customer = (await snap.ref.parent.parent.get()).data().customer_id;
      // Create a charge using the pushId as the idempotency key
      // to protect against double charges.
      const idempotencyKey = context.params.pushId;
      const payment = await stripe.paymentIntents.create(
        {
          amount,
          currency,
          customer,
          payment_method,
          off_session: false,
          confirm: true,
          confirmation_method: 'manual',
        },
        { idempotencyKey }
      );
      // If the result is successful, write it back to the database.
      await snap.ref.set(payment);
    } catch (error) {
      // We want to capture errors and render them in a user-friendly way, while
      // still logging an exception to Error Reporting.
      functions.logger.log(error);
      await snap.ref.set({ error: userFacingMessage(error) }, { merge: true });
      await reportError(error, { user: context.params.userId });
    }
  });

您可以通过ErrorContext参数传递用户详细信息。错误报告 UI 显示这些详细信息并使用它们来计算受影响用户的数量。

ErrorContext也可以传递有关 HTTP 请求的信息

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