CodeSampleX

Exemple

go.opentelemetry.io/otel v1.32.0: Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel

Échantillon vérifié pour golang go.opentelemetry.io/otel v1.32.0: Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with…

sha256:09bd889dee52c5ba1e03e35138e6f99814a113b3ace00a8708c010196e4d886f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go linux 24 · ubuntu · glibc 2.39 x64 go go gomod

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Cas

HOW
Objectif
Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel
Paquets
Symboles
  • otel.ErrorHandlerFunc
  • otel.GetErrorHandler
  • otel.Handle
  • otel.SetErrorHandler
Environnement
go
Créé
2026-08-27T10:21:53Z

Contrat

  1. otel.SetErrorHandler registers a custom ErrorHandler that receives errors dispatched via otel.Handle
  2. otel.GetErrorHandler returns the currently registered global ErrorHandler
  3. otel.ErrorHandlerFunc wraps an ordinary function into an ErrorHandler interface implementation
  4. otel.Handle directly dispatches errors including nil to the active ErrorHandler without panicking
  5. otel.Handle concurrently dispatches errors safely across multiple goroutines

Fichiers

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • otel_error_handler_test.go
  • spec.json

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# OpenTelemetry Go Global ErrorHandler and ErrorHandlerFunc Semantics

## Search Known Solution Result
A search for `pkg:golang/go.opentelemetry.io/otel@v1.32.0` identified existing samples covering baggage validation/propagation, `attribute.NewSet` slice mutation, and `attribute.Key` typed constructors:
- `sha256:7d96ce8c19aad54d6646ca788af8f4fcadf1aeda6a24ca303cfabacc5991341e` (*Baggage validation and CompositeTextMapPropagator*)
- `sha256:941874a3f6d0c964a2fd75094a1f5b9eaeb07fac3cb5a2e70c9510c4f1806c94` (*attribute.NewSet in-place mutation*)
- `sha256:d6b79fa424695504097254737bac05132ba5427c9395d5d988117af8a40f5846` (*attribute.Key typed constructors*)

This sample verifies distinct behavior in the root `go.opentelemetry.io/otel` package: global error handler configuration with `otel.SetErrorHandler`, handler retrieval with `otel.GetErrorHandler`, function wrapping with `otel.ErrorHandlerFunc`, and direct error dispatch via `otel.Handle`.

## Pinned Release
- `go.opentelemetry.io/otel`: `v1.32.0`

## Observed Behaviour
1. **Global Handler Registration and Retrieval**: `otel.SetErrorHandler(handler)` configures the global error handler, and `otel.GetErrorHandler()` returns the registered `otel.ErrorHandler` implementation.
2. **Custom ErrorHandler Implementation**: Structs implementing `Handle(err error)` receive errors dispatched by `otel.Handle(err)`.
3. **ErrorHandlerFunc Adapter**: `otel.ErrorHandlerFunc(func(err error) { ... })` adapts standalone functions to satisfy the `otel.ErrorHandler` interface.
4. **Direct Dispatch**: `otel.Handle(err)` directly delegates to `GetErrorHandler().Handle(err)`, passing the error (including `nil`) to the handler.
5. **Concurrent Dispatch**: Multiple goroutines concurrently invoking `otel.Handle(err)` execute without data races when the underlying handler protects shared state.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel@v1.32.0
Demonstrate these symbols/APIs:
  - otel.ErrorHandlerFunc
  - otel.GetErrorHandler
  - otel.Handle
  - otel.SetErrorHandler

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:04761b1d434e1c11ed8d0931b9f5d479771df82b4ad5c9dc10b4168e90610c05","contract":["otel.SetErrorHandler registers a custom ErrorHandler that receives errors dispatched via otel.Handle","otel.GetErrorHandler returns the currently registered global ErrorHandler","otel.ErrorHandlerFunc wraps an ordinary function into an ErrorHandler interface implementation","otel.Handle directly dispatches errors including nil to the active ErrorHandler without panicking","otel.Handle concurrently dispatches errors safely across multiple goroutines"],"goal":"Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel@v1.32.0"],"schemaVersion":1,"symbols":["otel.ErrorHandlerFunc","otel.GetErrorHandler","otel.Handle","otel.SetErrorHandler"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"gomod","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel@v1.32.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel@v1.32.0","symbols":["otel.ErrorHandlerFunc","otel.GetErrorHandler","otel.Handle","otel.SetErrorHandler"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otel-errorhandler

go 1.25.0

require go.opentelemetry.io/otel v1.32.0

require (
	github.com/go-logr/logr v1.4.4 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/stretchr/testify v1.10.0 // indirect
	go.opentelemetry.io/otel/metric v1.32.0 // indirect
	go.opentelemetry.io/otel/trace v1.32.0 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M=
go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8=
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
otel_error_handler_test.go
package main

import (
	"errors"
	"sync"
	"sync/atomic"
	"testing"

	"go.opentelemetry.io/otel"
)

type sliceErrorHandler struct {
	mu     sync.Mutex
	errors []error
}

func (s *sliceErrorHandler) Handle(err error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.errors = append(s.errors, err)
}

func TestCustomErrorHandlerAndGetSet(t *testing.T) {
	origHandler := otel.GetErrorHandler()
	defer otel.SetErrorHandler(origHandler)

	handler := &sliceErrorHandler{}
	otel.SetErrorHandler(handler)

	current := otel.GetErrorHandler()
	if current == nil {
		t.Fatalf("expected non-nil error handler from GetErrorHandler")
	}

	testErr := errors.New("span processing pipeline failure")
	otel.Handle(testErr)

	handler.mu.Lock()
	defer handler.mu.Unlock()

	if len(handler.errors) != 1 {
		t.Fatalf("expected 1 recorded error, got %d", len(handler.errors))
	}
	if !errors.Is(handler.errors[0], testErr) {
		t.Fatalf("expected error %v, got %v", testErr, handler.errors[0])
	}
}

func TestErrorHandlerFuncAndDispatch(t *testing.T) {
	origHandler := otel.GetErrorHandler()
	defer otel.SetErrorHandler(origHandler)

	var callCount int64
	var capturedErr error
	var mu sync.Mutex

	fnHandler := otel.ErrorHandlerFunc(func(err error) {
		atomic.AddInt64(&callCount, 1)
		mu.Lock()
		capturedErr = err
		mu.Unlock()
	})

	otel.SetErrorHandler(fnHandler)

	targetErr := errors.New("exporter connection timeout")
	otel.Handle(targetErr)

	if count := atomic.LoadInt64(&callCount); count != 1 {
		t.Fatalf("expected 1 handler invocation for target error, got %d", count)
	}
	mu.Lock()
	if capturedErr != targetErr {
		t.Fatalf("expected captured error %v, got %v", targetErr, capturedErr)
	}
	mu.Unlock()

	// Calling Handle with nil also invokes the registered handler directly
	otel.Handle(nil)
	if count := atomic.LoadInt64(&callCount); count != 2 {
		t.Fatalf("expected 2 handler invocations after nil error, got %d", count)
	}
	mu.Lock()
	if capturedErr != nil {
		t.Fatalf("expected captured nil error, got %v", capturedErr)
	}
	mu.Unlock()
}

func TestConcurrentErrorHandling(t *testing.T) {
	origHandler := otel.GetErrorHandler()
	defer otel.SetErrorHandler(origHandler)

	var totalCalls int64
	otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {
		atomic.AddInt64(&totalCalls, 1)
	}))

	const goroutines = 20
	const iterations = 50
	var wg sync.WaitGroup

	for i := 0; i < goroutines; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < iterations; j++ {
				otel.Handle(errors.New("concurrent exporter error"))
			}
		}()
	}

	wg.Wait()

	expectedTotal := int64(goroutines * iterations)
	if actual := atomic.LoadInt64(&totalCalls); actual != expectedTotal {
		t.Fatalf("expected %d total handler invocations, got %d", expectedTotal, actual)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel@v1.32.0"
  ],
  "symbols": [
    "otel.ErrorHandlerFunc",
    "otel.GetErrorHandler",
    "otel.Handle",
    "otel.SetErrorHandler"
  ]
}

Seeder d'origine

anonyme