Skip to content

Commit

Permalink
fix: refactor error reporting code sample (#3291)
Browse files Browse the repository at this point in the history
Align code sample for error reporting with code in other languages.
Use an explicit error with the "fixed" message.
Use "official" env variable name.
  • Loading branch information
minherz committed Sep 14, 2023
1 parent 0ed0158 commit 78dd4ac
Showing 1 changed file with 15 additions and 9 deletions.
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

0 comments on commit 78dd4ac

Please sign in to comment.