Cloud Run Functions에서 발생하는 런타임 오류를 처리하고 보고해야 합니다.
프로세스를 중단시키는 예외 또는 실행이 포착되지 않으면 일반적으로 최소화해야 하는 콜드 스타트가 발생할 수 있습니다.
함수가 함수 유형에 따라 오류를 알리도록 하기 위한 권장 방법은 다음과 같습니다.
HTTP 함수는 오류를 나타내는 적절한 HTTP 상태 코드를 반환해야 합니다. 자세한 내용은 HTTP 함수를 참조하세요.
이벤트 기반 함수는 오류 메시지를 로깅하고 반환해야 합니다. 자세한 내용은 이벤트 기반 함수 작성을 참조하세요.
오류가 적절하게 처리되면 오류가 발생한 함수 인스턴스가 활성 상태로 유지되고 요청을 처리할 수 있습니다.
Error Reporting에 오류 내보내기
다음과 같이 Cloud Run Functions에서 Error Reporting으로 오류를 내보낼 수 있습니다.
Node.js
// These WILL be reported to Error ReportingthrownewError('I failed you');// Will cause a cold start if not caught
Python
@functions_framework.httpdefhello_error_1(request):# This WILL be reported to Error Reporting,# and WILL NOT show up in logs or# terminate the function.fromgoogle.cloudimporterror_reportingclient=error_reporting.Client()try:raiseRuntimeError("I failed you")exceptRuntimeError:client.report_exception()# This WILL be reported to Error Reporting,# and WILL terminate the functionraiseRuntimeError("I failed you")@functions_framework.httpdefhello_error_2(request):# These errors WILL NOT be reported to Error# Reporting, but will show up in logs.importloggingimportsysprint(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.fromflaskimportabortreturnabort(500)
Go
packagetipsimport("fmt""net/http""os""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit(){functions.HTTP("HTTPError",HTTPError)}// HTTPError describes how errors are handled in an HTTP function.funcHTTPError(whttp.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)")}
자바
importcom.google.cloud.functions.HttpFunction;importcom.google.cloud.functions.HttpRequest;importcom.google.cloud.functions.HttpResponse;importjava.io.IOException;importjava.util.logging.Logger;publicclassHelloErrorimplementsHttpFunction{privatestaticfinalLoggerlogger=Logger.getLogger(HelloError.class.getName());@Overridepublicvoidservice(HttpRequestrequest,HttpResponseresponse)throwsIOException{// These will NOT be reported to Error ReportingSystem.err.println("I failed you");logger.severe("I failed you");// This WILL be reported to Error ReportingthrownewRuntimeException("I failed you");}}
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[[["\u003cp\u003eCloud Run functions should handle and report runtime errors to avoid cold starts, which can negatively impact performance.\u003c/p\u003e\n"],["\u003cp\u003eHTTP functions should signal errors by returning appropriate HTTP status codes, while event-driven functions should log and return an error message.\u003c/p\u003e\n"],["\u003cp\u003eErrors can be emitted to Error Reporting, enabling centralized error tracking and management, which is demonstrated in the code examples provided for Node.js, Python, Go, and Java.\u003c/p\u003e\n"],["\u003cp\u003eUncaught exceptions, particularly asynchronous ones, will be reported to Error Reporting and may lead to cold starts on future invocations, impacting the function's execution time.\u003c/p\u003e\n"],["\u003cp\u003eWhile various methods such as printing errors to stdout, stderr, or logging errors do not report errors to error reporting, they are recorded in the logs.\u003c/p\u003e\n"]]],[],null,["# Report runtime function errors (1st gen)\n========================================\n\nYou should handle and report runtime errors that occur in Cloud Run functions.\nUncaught exceptions or executions that crash the process can result in\n[cold starts](/functions/1stgendocs/concepts/execution-environment#cold-starts),\nwhich you should generally try to minimize.\n\nThe recommended way for a function to signal an error depends on the function\ntype:\n\n- HTTP functions should return appropriate HTTP status codes which denote an\n error. See [HTTP Functions](/functions/1stgendocs/writing/write-http-functions)\n for more information.\n\n- Event-driven functions should log and return an error message. See\n [Write event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions)\n for more information.\n\nIf errors are appropriately handled, then function instances that encounter\nerrors can remain active and available to serve requests.\n\nEmit errors to Error Reporting\n------------------------------\n\nYou can emit an error from a Cloud Run function to\n[Error Reporting](https://cloud.google.com/error-reporting/docs) as shown in the following: \n\n### Node.js\n\n // These WILL be reported to Error Reporting\n throw new Error('I failed you'); // Will cause a cold start if not caught\n\n### Python\n\n @functions_framework.http\n def hello_error_1(request):\n # This WILL be reported to Error Reporting,\n # and WILL NOT show up in logs or\n # terminate the function.\n from google.cloud import error_reporting\n\n client = error_reporting.https://cloud.google.com/python/docs/reference/clouderrorreporting/latest/google.cloud.error_reporting.client.Client.html()\n\n try:\n raise RuntimeError(\"I failed you\")\n except RuntimeError:\n https://cloud.google.com/python/docs/reference/clouderrorreporting/latest/google.cloud.error_reporting.client.html.https://cloud.google.com/python/docs/reference/clouderrorreporting/latest/google.cloud.error_reporting.client.Client.html#google_cloud_error_reporting_client_Client_report_exception()\n\n # This WILL be reported to Error Reporting,\n # and WILL terminate the function\n raise RuntimeError(\"I failed you\")\n\n\n @functions_framework.http\n def hello_error_2(request):\n # These errors WILL NOT be reported to Error\n # Reporting, but will show up in logs.\n import logging\n import sys\n\n print(RuntimeError(\"I failed you (print to stdout)\"))\n logging.warning(RuntimeError(\"I failed you (logging.warning)\"))\n logging.error(RuntimeError(\"I failed you (logging.error)\"))\n sys.stderr.write(\"I failed you (sys.stderr.write)\\n\")\n\n # This is considered a successful execution and WILL NOT be reported\n # to Error Reporting, but the status code (500) WILL be logged.\n from flask import abort\n\n return abort(500)\n\n### Go\n\n\n package tips\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n \t\"os\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n func init() {\n \tfunctions.HTTP(\"HTTPError\", HTTPError)\n }\n\n // HTTPError describes how errors are handled in an HTTP function.\n func HTTPError(w http.ResponseWriter, r *http.Request) {\n \t// An error response code is NOT reported to Error Reporting.\n \t// http.Error(w, \"An error occurred\", http.StatusInternalServerError)\n\n \t// Printing to stdout and stderr is NOT reported to Error Reporting.\n \tfmt.Println(\"An error occurred (stdout)\")\n \tfmt.Fprintln(os.Stderr, \"An error occurred (stderr)\")\n\n \t// Calling log.Fatal sets a non-zero exit code and is NOT reported to Error\n \t// Reporting.\n \t// log.Fatal(\"An error occurred (log.Fatal)\")\n\n \t// Panics are reported to Error Reporting.\n \tpanic(\"An error occurred (panic)\")\n }\n\n### Java\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.IOException;\n import java.util.logging.Logger;\n\n public class HelloError implements HttpFunction {\n\n private static final Logger logger = Logger.getLogger(HelloError.class.getName());\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n // These will NOT be reported to Error Reporting\n System.err.println(\"I failed you\");\n logger.severe(\"I failed you\");\n\n // This WILL be reported to Error Reporting\n throw new RuntimeException(\"I failed you\");\n }\n }\n\nIf you would like more fine-grained error reporting, you can use the [Error\nReporting client\nlibraries](/error-reporting/docs/reference/libraries).\n\nYou can view the reported errors in [Error Reporting](https://console.cloud.google.com/errors)\nin the Google Cloud console. You can also see the errors reported from a\nparticular function when you select it from the [list of functions](https://console.cloud.google.com/functions) in the Google Cloud console.\n\nUncaught exceptions produced by your function will appear in Error Reporting.\nNote that some types of uncaught exceptions (such as those thrown\nasynchronously) will cause a [cold\nstart](/functions/1stgendocs/concepts/execution-environment#cold-starts) to occur upon\na future function invocation. This increases the amount of time your function\nwill take to run."]]