ランタイム関数のエラーを報告する

Cloud Functions の関数で発生したランタイム エラーを処理して報告する必要があります。キャッチされない例外やプロセスがクラッシュする例外が発生すると、コールド スタートが発生する可能性があります。これは、最小限に抑える必要があります。

関数でエラーを通知するための推奨されている方法は、関数の種類によって異なります。

  • HTTP 関数は、エラーを示す適切な HTTP ステータス コードを返す必要があります。詳細については、HTTP 関数をご覧ください。

  • イベント ドリブン関数は、エラー メッセージをロギングして返す必要があります。詳細については、バックグラウンド関数CloudEvent 関数をご覧ください。

エラーが適切に処理されていれば、エラーが発生した関数インスタンスは引き続きアクティブになり、リクエストを処理できます。

Error Reporting にエラーを出力する

次のように、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)

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 に表示されます。キャッチされなかった例外(非同期でスローされた例外など)は、将来の関数呼び出しでコールド スタートの原因となる可能性があります。これにより、関数の実行時間が長くなります。