-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors_test.go
More file actions
67 lines (58 loc) · 2.25 KB
/
errors_test.go
File metadata and controls
67 lines (58 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package errors_test
import (
"bytes"
"encoding/json"
"fmt"
"log/slog"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/talon-one/errors"
)
func TestLogNewErrorWithSlog(t *testing.T) {
logOutput := bytes.NewBuffer([]byte{})
logger := slog.New(slog.NewJSONHandler(logOutput, &slog.HandlerOptions{}))
err := errors.New("an internal server error occurred", errors.WithKind("server-side"))
errors.Annotate(err, "current_user", "demo-user@example.com")
logger.Error("an error occurred", "err", err)
t.Log(logOutput.String())
logMessage := map[string]any{}
err = json.Unmarshal(logOutput.Bytes(), &logMessage)
require.NoError(t, err)
assert.Equal(t, "ERROR", logMessage["level"])
assert.Equal(t, "an error occurred", logMessage["msg"])
assert.NotNil(t, logMessage["time"])
require.NotNil(t, logMessage["err"])
errMap, ok := logMessage["err"].(map[string]any)
require.True(t, ok)
assert.Len(t, errMap, 4)
assert.Equal(t, "server-side", errMap["kind"])
assert.Equal(t, "an internal server error occurred", errMap["message"])
require.NotNil(t, errMap["annotations"])
annotationsMap, ok := errMap["annotations"].(map[string]any)
require.True(t, ok)
assert.Len(t, annotationsMap, 1)
assert.Equal(t, "demo-user@example.com", annotationsMap["current_user"])
assert.NotEmpty(t, errMap["stacktrace"])
assert.Equal(t, 4, strings.Count(errMap["stacktrace"].(string), "\n"))
}
func TestPrintErrorWithFormat(t *testing.T) {
err := errors.New("an internal server error occurred", errors.WithKind("server-side"))
errors.Annotate(err, "current_user", "demo-user@example.com")
output := fmt.Sprintf("%+v", err)
t.Log(output)
errMap := map[string]any{}
err = json.Unmarshal([]byte(output), &errMap)
require.NoError(t, err)
assert.Len(t, errMap, 4)
assert.Equal(t, "server-side", errMap["kind"])
assert.Equal(t, "an internal server error occurred", errMap["message"])
require.NotNil(t, errMap["annotations"])
annotationsMap, ok := errMap["annotations"].(map[string]any)
require.True(t, ok)
assert.Len(t, annotationsMap, 1)
assert.Equal(t, "demo-user@example.com", annotationsMap["current_user"])
assert.NotEmpty(t, errMap["stacktrace"])
assert.Equal(t, 4, strings.Count(errMap["stacktrace"].(string), "\n"))
}