Firebase is back at Google I/O on May 10! Register now

Segnala errori

Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.

Segnalazione automatica degli errori

Puoi emettere un errore da una funzione cloud a Error Reporting come mostrato di seguito:

Node.js

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

Se desideri una segnalazione degli errori più granulare, puoi utilizzare le librerie client per la segnalazione degli errori .

Puoi visualizzare gli errori segnalati in Error Reporting nella console di GCP. Puoi anche vedere gli errori segnalati da una particolare funzione quando la selezioni dall'elenco delle funzioni nella console di GCP.

Le eccezioni non rilevate prodotte dalla tua funzione verranno visualizzate in Segnalazione errori. Si noti che alcuni tipi di eccezioni non rilevate (come quelle lanciate in modo asincrono) provocheranno un avvio a freddo su una futura chiamata di funzione. Ciò aumenta il tempo necessario per l'esecuzione della funzione.

Segnalazione manuale degli errori

Per segnalare un errore a Error Reporting da una funzione, utilizza l'API Cloud Logging .

Importazione delle dipendenze

Dalla tua directory functions , installa la libreria client Cloud Logging per Node.js:

npm install --save @google-cloud/logging

Importa e inizializza la libreria client di Cloud Logging:

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

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

Invio a Cloud Logging

Una voce di registro correttamente formata richiede un oggetto MonitoredResource e un oggetto ErrorEvent .

Questa funzione reportError di esempio illustra i dati minimi richiesti per segnalare un errore a Segnalazione errori.

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

La funzione reportError può essere utilizzata per segnalare manualmente gli errori:

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

Puoi passare i dettagli dell'utente tramite il parametro ErrorContext . L'interfaccia utente di Segnalazione errori visualizza questi dettagli e li utilizza per calcolare il numero di utenti interessati.

ErrorContext può anche ricevere informazioni su una richiesta 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();
  });
});
,

Segnalazione automatica degli errori

Puoi emettere un errore da una funzione cloud a Error Reporting come mostrato di seguito:

Node.js

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

Se desideri una segnalazione degli errori più granulare, puoi utilizzare le librerie client per la segnalazione degli errori .

Puoi visualizzare gli errori segnalati in Error Reporting nella console di GCP. Puoi anche vedere gli errori segnalati da una particolare funzione quando la selezioni dall'elenco delle funzioni nella console di GCP.

Le eccezioni non rilevate prodotte dalla tua funzione verranno visualizzate in Segnalazione errori. Si noti che alcuni tipi di eccezioni non rilevate (come quelle lanciate in modo asincrono) provocheranno un avvio a freddo su una futura chiamata di funzione. Ciò aumenta il tempo necessario per l'esecuzione della funzione.

Segnalazione manuale degli errori

Per segnalare un errore a Error Reporting da una funzione, utilizza l'API Cloud Logging .

Importazione delle dipendenze

Dalla tua directory functions , installa la libreria client Cloud Logging per Node.js:

npm install --save @google-cloud/logging

Importa e inizializza la libreria client di Cloud Logging:

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

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

Invio a Cloud Logging

Una voce di registro correttamente formata richiede un oggetto MonitoredResource e un oggetto ErrorEvent .

Questa funzione reportError di esempio illustra i dati minimi richiesti per segnalare un errore a Segnalazione errori.

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

La funzione reportError può essere utilizzata per segnalare manualmente gli errori:

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

Puoi passare i dettagli dell'utente tramite il parametro ErrorContext . L'interfaccia utente di Segnalazione errori visualizza questi dettagli e li utilizza per calcolare il numero di utenti interessati.

ErrorContext può anche ricevere informazioni su una richiesta 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();
  });
});