Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor error reporting code sample #3291

Merged
merged 3 commits into from Sep 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 15 additions & 9 deletions errorreporting/errorreporting_quickstart/main.go
Expand Up @@ -21,41 +21,47 @@ package main

import (
"context"
"errors"
"log"
"net/http"
"os"

"cloud.google.com/go/errorreporting"
)

var errorClient *errorreporting.Client

func main() {
ctx := context.Background()

// Sets your Google Cloud Platform project ID.
projectID := "YOUR_PROJECT_ID"
// Set your Google Cloud Platform project ID via environment or explicitly
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
args := os.Args[1:]
if len(args) > 0 && args[0] != "" {
projectID = args[0]
}

ctx := context.Background()
var err error
errorClient, err = errorreporting.NewClient(ctx, projectID, errorreporting.Config{
ServiceName: "myservice",
ServiceName: "errorreporting_quickstart",
ServiceVersion: "0.0.0",
OnError: func(err error) {
log.Printf("Could not log error: %v", err)
log.Printf("Could not report the error: %v", err)
},
})
if err != nil {
log.Fatal(err)
}
defer errorClient.Close()

resp, err := http.Get("not-a-valid-url")
err = errors.New("something went wrong")
if err != nil {
logAndPrintError(err)
return
}
log.Print(resp.Status)
}

func logAndPrintError(err error) {
/// Client autopopulates the error context of the error. For more details about the context see:
/// https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorContext
errorClient.Report(errorreporting.Entry{
Error: err,
})
Expand Down