CodeSampleX

샘플

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

검증된 샘플 — golang go.opentelemetry.io/otel v1.32.0: Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler…

sha256:09bd889dee52c5ba1e03e35138e6f99814a113b3ace00a8708c010196e4d886f

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go linux 24 · ubuntu · glibc 2.39 x64 go go gomod

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Demonstrate global ErrorHandler and ErrorHandlerFunc configuration with otel.SetErrorHandler, otel.GetErrorHandler, and error dispatch via otel.Handle in go.opentelemetry.io/otel
패키지
심벌
  • otel.ErrorHandlerFunc
  • otel.GetErrorHandler
  • otel.Handle
  • otel.SetErrorHandler
환경
go
생성일
2026-08-27T10:21:53Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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"
  ]
}

오리진 시더

익명