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-04-11(UTC)"],[[["Cloud Run functions should handle and report runtime errors to prevent cold starts and maintain availability."],["HTTP functions should use appropriate HTTP status codes to signal errors, while event-driven functions should log and return error messages."],["Unhandled exceptions in Node.js, Python, and Go runtimes are surfaced to the function caller and should be reviewed to ensure no sensitive information is exposed."],["Errors can be emitted to Error Reporting using language-specific methods, and some methods, like raising an exception, will both report and terminate the function, while other approaches may not terminate it."],["Uncaught exceptions are reported in Error Reporting and can lead to cold starts, which increase function execution time, so it's best to try to handle errors."]]],[]]