Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Informar erros de função de tempo de execução (1a geração)
Trate e relate erros de ambiente de execução que ocorrem no Cloud Run functions.
Execuções ou exceções não identificadas que causam falhas no processo podem resultar em inicializações a frio, o que geralmente você deve tentar minimizar.
A maneira recomendada para uma função sinalizar um erro depende do tipo de
função:
As funções HTTP retornarão códigos de status HTTP apropriados que denotarem um
erro. Consulte Funções HTTP para mais informações.
As funções orientadas a eventos precisam registrar e retornar uma mensagem de erro. Consulte
Escrever funções orientadas a eventos
para mais informações.
Se os erros forem tratados adequadamente, as instâncias de função que encontrarem erros poderão permanecer ativas e disponíveis para atender às solicitações.
Informar erros ao Error Reporting
É possível emitir um erro de uma função do Cloud Run para o Error Reporting, conforme mostrado abaixo:
Node.js
// These WILL be reported to Error ReportingthrownewError('I failed you');// Will cause a cold start if not caught
Python
@functions_framework.httpdefhello_error_1(request):# This WILL be reported to Error Reporting,# and WILL NOT show up in logs or# terminate the function.fromgoogle.cloudimporterror_reportingclient=error_reporting.Client()try:raiseRuntimeError("I failed you")exceptRuntimeError:client.report_exception()# This WILL be reported to Error Reporting,# and WILL terminate the functionraiseRuntimeError("I failed you")@functions_framework.httpdefhello_error_2(request):# These errors WILL NOT be reported to Error# Reporting, but will show up in logs.importloggingimportsysprint(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.fromflaskimportabortreturnabort(500)
Go
packagetipsimport("fmt""net/http""os""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit(){functions.HTTP("HTTPError",HTTPError)}// HTTPError describes how errors are handled in an HTTP function.funcHTTPError(whttp.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
importcom.google.cloud.functions.HttpFunction;importcom.google.cloud.functions.HttpRequest;importcom.google.cloud.functions.HttpResponse;importjava.io.IOException;importjava.util.logging.Logger;publicclassHelloErrorimplementsHttpFunction{privatestaticfinalLoggerlogger=Logger.getLogger(HelloError.class.getName());@Overridepublicvoidservice(HttpRequestrequest,HttpResponseresponse)throwsIOException{// These will NOT be reported to Error ReportingSystem.err.println("I failed you");logger.severe("I failed you");// This WILL be reported to Error ReportingthrownewRuntimeException("I failed you");}}
Para conferir os erros registrados, use o Error Reporting
no console Google Cloud . Você também pode conferir os erros registrados de uma função específica quando a seleciona na lista de funções no console Google Cloud .
As exceções não identificadas que foram produzidas pela função serão exibidas no Error
Reporting.
Alguns tipos de exceções não identificadas (como as geradas de forma
assíncrona) farão com que uma inicialização a frio
ocorra em uma invocação futura de uma função. Isso aumenta o tempo de execução da função.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-07-14 UTC."],[[["Cloud Run functions should handle and report runtime errors to avoid cold starts, which can negatively impact performance."],["HTTP functions should signal errors by returning appropriate HTTP status codes, while event-driven functions should log and return an error message."],["Errors can be emitted to Error Reporting, enabling centralized error tracking and management, which is demonstrated in the code examples provided for Node.js, Python, Go, and Java."],["Uncaught exceptions, particularly asynchronous ones, will be reported to Error Reporting and may lead to cold starts on future invocations, impacting the function's execution time."],["While various methods such as printing errors to stdout, stderr, or logging errors do not report errors to error reporting, they are recorded in the logs."]]],[]]