Báo cáo lỗi

Tự động báo cáo lỗi

Bạn có thể phát thông báo lỗi từ một Hàm đám mây để Báo cáo lỗi như minh hoạ dưới đây:

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)

Nếu muốn báo cáo lỗi chi tiết hơn, bạn có thể sử dụng Thư viện ứng dụng Báo cáo lỗi.

Bạn có thể xem các lỗi được báo cáo trong phần Error Reporting (Báo cáo lỗi) trên Bảng điều khiển của Google Cloud Platform (GCP). Bạn cũng có thể xem các lỗi được báo cáo qua một hàm cụ thể khi chọn hàm đó trong danh sách hàm trong Bảng điều khiển GCP.

Các ngoại lệ chưa phát hiện được do hàm của bạn tạo ra sẽ xuất hiện trong Báo cáo lỗi. Xin lưu ý rằng một số loại trường hợp ngoại lệ chưa được nắm bắt (chẳng hạn như các trường hợp được gửi không đồng bộ) sẽ khiến quá trình khởi động nguội xảy ra khi một lệnh gọi hàm trong tương lai. Điều này sẽ làm tăng thời gian chạy hàm của bạn.

Báo cáo lỗi theo cách thủ công

Gửi đến Cloud Logging

Hàm error trong SDK trình ghi nhật ký của Cloud Functions sẽ báo cáo lỗi cho cả tính năng Ghi nhật ký trên đám mây và Báo cáo lỗi. Để đưa thêm ngữ cảnh từ lỗi vào dưới dạng dữ liệu có cấu trúc, hãy truyền một đối tượng lỗi làm đối số thứ hai:

} catch (err) {
  // Attach an error object as the second argument
  functions.logger.error(
    "Unable to read quote from Firestore, sending default instead",
    err
  );
}