回報錯誤

自動回報錯誤

您可以如下所示,將錯誤從 Cloud 函式發送至 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 記錄器 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
  );
}