报告错误

自动报告错误

您可以将 Cloud Functions 函数报告的错误提交到 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)

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

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

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

手动报告错误

发送到 Cloud Logging

Cloud Functions logger SDK 中的 error 函数会将错误同时报告给 Cloud Logging 和 Error Reporting。如需将错误的更多情境信息作为结构化数据包含在内,请将错误对象作为第二个参数传递:

} catch (err) {
  // Attach an error object as the second argument
  functions.logger.error(
    "Unable to read quote from Firestore, sending default instead",
    err
  );
}