Automatyczne raportowanie błędów
Możesz zgłosić błąd z Cloud Functions do Error Reporting , jak pokazano poniżej:
Node.js
Jeśli potrzebujesz bardziej szczegółowych raportów o błędach, możesz skorzystać z bibliotek klienckich Raportowania błędów .
Zgłoszone błędy możesz zobaczyć w Raportowaniu błędów w konsoli GCP. Błędy zgłoszone przez konkretną funkcję możesz też zobaczyć po wybraniu jej z listy funkcji w konsoli GCP.
Nieprzechwycone wyjątki wygenerowane przez Twoją funkcję pojawią się w raportowaniu błędów. Należy zauważyć, że niektóre typy nieprzechwyconych wyjątków (takie jak te zgłaszane asynchronicznie) spowodują zimny start przy przyszłym wywołaniu funkcji. Zwiększa to czas potrzebny na uruchomienie funkcji.
Ręczne zgłaszanie błędów
Aby zgłosić błąd do Error Reporting z poziomu funkcji, użyj Cloud Logging API.
Importowanie zależności
Z katalogu functions
zainstaluj bibliotekę klienta Cloud Logging dla Node.js:
npm install --save @google-cloud/logging
Zaimportuj i zainicjuj bibliotekę klienta Cloud Logging:
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
Wysyłanie do Cloud Logging
Prawidłowo sformułowany wpis dziennika wymaga obiektu MonitoredResource
i obiektu ErrorEvent
.
Ta przykładowa funkcja reportError
pokazuje minimalną ilość danych wymaganych do zgłoszenia błędu do Error Reporting.
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
można użyć do ręcznego zgłaszania błędów:
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 }); } });
Możesz przekazać szczegółowe informacje o użytkowniku za pomocą parametru ErrorContext
. Interfejs raportowania błędów wyświetla te szczegóły i wykorzystuje je do obliczenia liczby użytkowników, których dotyczy problem.
ErrorContext
można również przekazać informacje w żądaniu 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();
});
});