Skip to content

Commit b3886a6

Browse files
feat: expose Desc error through public Err() method (#1902)
* feat: expose Desc error through public Err() method Adds a public Err() method to Desc type to allow users to check if an error occurred during descriptor construction. Previously, the error field was private and inaccessible. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> Signed-off-by: Yuri Nikolic <[email protected]> * Fixing review findings Signed-off-by: Yuri Nikolic <[email protected]> * Fixing failing test Signed-off-by: Yuri Nikolic <[email protected]> --------- Signed-off-by: Yuri Nikolic <[email protected]> Co-authored-by: Claude <[email protected]>
1 parent 9050000 commit b3886a6

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

prometheus/desc.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,15 @@ func NewInvalidDesc(err error) *Desc {
182182
}
183183
}
184184

185+
// Err returns an error that occurred during construction, if any.
186+
//
187+
// Calling this method is optional. It can be used to detect construction
188+
// errors early, before invoking other methods on the Desc. If an error is
189+
// present, later operations may not behave as expected.
190+
func (d *Desc) Err() error {
191+
return d.err
192+
}
193+
185194
func (d *Desc) String() string {
186195
lpStrings := make([]string, 0, len(d.constLabelPairs))
187196
for _, lp := range d.constLabelPairs {

prometheus/desc_test.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,29 @@ import (
1717
"testing"
1818
)
1919

20-
func TestNewDescInvalidLabelValues(t *testing.T) {
20+
func TestNewDescInvalidConstLabelValues(t *testing.T) {
21+
labelValue := "\xFF"
2122
desc := NewDesc(
2223
"sample_label",
2324
"sample label",
2425
nil,
25-
Labels{"a": "\xFF"},
26+
Labels{"a": labelValue},
2627
)
27-
if desc.err == nil {
28-
t.Errorf("NewDesc: expected error because: %s", desc.err)
28+
if desc.Err() == nil {
29+
t.Errorf("NewDesc: expected error because const label value is invalid: %s", labelValue)
30+
}
31+
}
32+
33+
func TestNewDescInvalidVariableLabelName(t *testing.T) {
34+
labelValue := "__label__"
35+
desc := NewDesc(
36+
"sample_label",
37+
"sample label",
38+
[]string{labelValue},
39+
Labels{"a": "b"},
40+
)
41+
if desc.Err() == nil {
42+
t.Errorf("NewDesc: expected error because variable label name is invalid: %s", labelValue)
2943
}
3044
}
3145

@@ -36,8 +50,8 @@ func TestNewDescNilLabelValues(t *testing.T) {
3650
nil,
3751
nil,
3852
)
39-
if desc.err != nil {
40-
t.Errorf("NewDesc: unexpected error: %s", desc.err)
53+
if desc.Err() != nil {
54+
t.Errorf("NewDesc: unexpected error: %s", desc.Err())
4155
}
4256
}
4357

0 commit comments

Comments
 (0)