报告运行时函数错误(第 1 代)

您应该处理和报告 Cloud Functions 函数中发生的运行时错误。 未捕获到的可引发进程崩溃的异常或执行可能会导致冷启动,而您一般应尝试最大限度地减少冷启动次数。

对于如何让函数发出信号来指示出错,建议的方式根据函数类型而有所不同:

  • HTTP 函数应该返回可指明具体错误的适当 HTTP 状态代码。如需了解详情,请参阅 HTTP 函数

  • 事件驱动的函数应记录并返回错误消息。如需了解详情,请参阅编写事件驱动型函数

如果适当处理了错误,则发生错误的函数实例可以保持活动状态并可用于处理请求。

向 Error Reporting 发送错误

您可以将 Cloud Run 函数报告的错误提交到 Error Reporting,如下所示:

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

如果您需要更精细的错误报告功能,可以使用 Error Reporting 客户端库

您可以在 Google Cloud 控制台的 Error Reporting 中查看报告的错误。您也可以在 Google Cloud 控制台的函数列表中选择特定的函数,来查看该函数报告的错误。

您的函数产生的未捕获到的异常会显示在 Error Reporting 中。请注意,未捕获到的某些异常(例如异步抛出的异常)会导致在未来调用函数时执行冷启动,这会增加您的函数运行所需的时间。