Segnala errori di runtime della funzione (1ª generazione.)

Devi gestire e segnalare gli errori di runtime che si verificano nelle funzioni Cloud Run. Le eccezioni non rilevate o le esecuzioni che causano l'arresto anomalo del processo possono comportare avvii a freddo, che in genere dovresti cercare di ridurre al minimo.

Il modo consigliato per segnalare un errore dipende dal tipo di funzione:

  • Le funzioni HTTP devono restituire codici di stato HTTP appropriati che indicano un errore. Per saperne di più, consulta Funzioni HTTP.

  • Le funzioni basate su eventi devono registrare e restituire un messaggio di errore. Per saperne di più, consulta Scrivere funzioni basate sugli eventi.

Se gli errori vengono gestiti in modo appropriato, le istanze di funzione che riscontrano errori possono rimanere attive e disponibili per gestire le richieste.

Emettere errori in Error Reporting

Puoi generare un errore da una funzione Cloud Run 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

Python

@functions_framework.http
def hello_error_1(request):
    # This WILL be reported to Error Reporting,
    # and WILL NOT show up in logs or
    # terminate the function.
    from google.cloud import error_reporting

    client = error_reporting.Client()

    try:
        raise RuntimeError("I failed you")
    except RuntimeError:
        client.report_exception()

    # This WILL be reported to Error Reporting,
    # and WILL terminate the function
    raise RuntimeError("I failed you")


@functions_framework.http
def hello_error_2(request):
    # These errors WILL NOT be reported to Error
    # Reporting, but will show up in logs.
    import logging
    import sys

    print(RuntimeError("I failed you (print to stdout)"))
    logging.warning(RuntimeError("I failed you (logging.warning)"))
    logging.error(RuntimeError("I failed you (logging.error)"))
    sys.stderr.write("I failed you (sys.stderr.write)\n")

    # This is considered a successful execution and WILL NOT be reported
    # to Error Reporting, but the status code (500) WILL be logged.
    from flask import abort

    return abort(500)

Go


package tips

import (
	"fmt"
	"net/http"
	"os"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

func init() {
	functions.HTTP("HTTPError", HTTPError)
}

// HTTPError describes how errors are handled in an HTTP function.
func HTTPError(w http.ResponseWriter, r *http.Request) {
	// An error response code is NOT reported to Error Reporting.
	// http.Error(w, "An error occurred", http.StatusInternalServerError)

	// Printing to stdout and stderr is NOT reported to Error Reporting.
	fmt.Println("An error occurred (stdout)")
	fmt.Fprintln(os.Stderr, "An error occurred (stderr)")

	// Calling log.Fatal sets a non-zero exit code and is NOT reported to Error
	// Reporting.
	// log.Fatal("An error occurred (log.Fatal)")

	// Panics are reported to Error Reporting.
	panic("An error occurred (panic)")
}

Java


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.util.logging.Logger;

public class HelloError implements HttpFunction {

  private static final Logger logger = Logger.getLogger(HelloError.class.getName());

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    // These will NOT be reported to Error Reporting
    System.err.println("I failed you");
    logger.severe("I failed you");

    // This WILL be reported to Error Reporting
    throw new RuntimeException("I failed you");
  }
}

Se vuoi un report sugli errori più granulare, puoi utilizzare le librerie client di Error Reporting.

Puoi visualizzare gli errori segnalati in Error Reporting nella console Google Cloud . Puoi anche visualizzare gli errori segnalati da una funzione specifica quando la selezioni dall'elenco delle funzioni nella console Google Cloud .

Le eccezioni non rilevate prodotte dalla tua funzione verranno visualizzate in Error Reporting. Tieni presente che alcuni tipi di eccezioni non rilevate (ad esempio quelle generate in modo asincrono) causeranno un avvio a freddo in una successiva chiamata di funzione. In questo modo, il tempo di esecuzione della funzione aumenterà.