報告錯誤

自動報告錯誤

您可以從雲函數向錯誤報告發出錯誤,如下所示:

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)

如果您想要更細粒度的錯誤報告,可以使用錯誤報告用戶端程式庫

您可以在 GCP Console 的錯誤報告中查看報告的錯誤。當您從 GCP Console 的函數清單中選擇特定函數時,您也可以查看該函數報告的錯誤。

您的函數產生的未捕獲的異常將出現在錯誤報告中。請注意,某些類型的未捕獲異常(例如非同步引發的異常)將導致未來函數呼叫時發生冷啟動。這會增加函數運行所需的時間。

手動報告錯誤

傳送至雲端日誌

Cloud Functions記錄器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
  );
}