The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
grafana/pkg/util/errutil/template_test.go

73 lines
1.9 KiB

package errutil_test
import (
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/util/errutil"
)
func TestTemplate(t *testing.T) {
tmpl := errutil.Internal("template.sampleError").MustTemplate("[{{ .Public.user }}] got error: {{ .Error }}")
err := tmpl.Build(errutil.TemplateData{
Public: map[string]any{
"user": "grot the bot",
},
Error: errors.New("oh noes"),
})
t.Run("Built error should return true when compared with templated error ", func(t *testing.T) {
require.True(t, errors.Is(err, tmpl))
})
t.Run("Built error should return true when compared with templated error base ", func(t *testing.T) {
require.True(t, errors.Is(err, tmpl.Base))
})
}
func ExampleTemplate() {
// Initialization, this is typically done on a package or global
// level.
var tmpl = errutil.Internal("template.sampleError").MustTemplate("[{{ .Public.user }}] got error: {{ .Error }}")
// Construct an error based on the template.
err := tmpl.Build(errutil.TemplateData{
Public: map[string]any{
"user": "grot the bot",
},
Error: errors.New("oh noes"),
})
fmt.Println(err.Error())
// Output:
// [template.sampleError] [grot the bot] got error: oh noes
}
func ExampleTemplate_public() {
// Initialization, this is typically done on a package or global
// level.
var tmpl = errutil.Internal("template.sampleError").MustTemplate(
"[{{ .Public.user }}] got error: {{ .Error }}",
errutil.WithPublic("Oh, no, error for {{ .Public.user }}"),
)
// Construct an error based on the template.
//nolint:errorlint
err := tmpl.Build(errutil.TemplateData{
Public: map[string]any{
"user": "grot the bot",
},
Error: errors.New("oh noes"),
}).(errutil.Error)
fmt.Println(err.Error())
fmt.Println(err.PublicMessage)
// Output:
// [template.sampleError] [grot the bot] got error: oh noes
// Oh, no, error for grot the bot
}