Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions compatible_shim.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,10 @@ func (e *Error) UnmarshalJSON(data []byte) error {
}
e.code = ErrCode(tErr.Code)
e.message = tErr.Msg
e.args = nil
e.cause = nil
e.redactArgsPos = nil
e.file = ""
e.line = 0
return nil
}
58 changes: 58 additions & 0 deletions compatible_shim_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package errors

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
)

func TestUnmarshalJSONClearsLocalState(t *testing.T) {
e := Error{
message: "old %s",
args: []any{"secret"},
cause: New("old cause"),
redactArgsPos: []int{0},
file: "old.go",
line: 42,
}
const message = "literal %s, %1000000[1]d, 95% full"
require.NoError(t, e.UnmarshalJSON([]byte(`{"class":6,"code":123,"message":"`+message+`","rfccode":"executor:123"}`)))
require.Empty(t, e.Args())
require.Equal(t, message, e.GetMsg())
require.Equal(t, Error{
code: 123,
codeText: "executor:123",
message: message,
}, e)

data, err := json.Marshal(&e)
require.NoError(t, err)
var decoded jsonError
require.NoError(t, json.Unmarshal(data, &decoded))
require.Equal(t, message, decoded.Msg)
}

func TestUnmarshalJSONInvalidInputPreservesError(t *testing.T) {
for _, input := range []string{
`{"message":"new message",`,
`{"message":"new message","code":"invalid"}`,
} {
t.Run(input, func(t *testing.T) {
e := Error{
code: 123,
codeText: "executor:123",
message: "old %s",
args: []any{"secret"},
cause: New("old cause"),
redactArgsPos: []int{0},
file: "old.go",
line: 42,
}
before := e
require.Error(t, e.UnmarshalJSON([]byte(input)))
require.Equal(t, before, e)
require.Equal(t, "old secret", e.GetMsg())
})
}
}
18 changes: 12 additions & 6 deletions normalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,23 +360,29 @@ func (e *Error) Cause() error {
return root
}

func (e *Error) FastGenWithCause(args ...any) error {
// FastGenWithCause generates a stackless error with the same class and code,
// using the cause's error text as a literal message without formatting arguments.
// Only use it as errorTemplate.Wrap(err).FastGenWithCause().
// To format the template with arguments, use FastGenByArgs instead.
func (e *Error) FastGenWithCause() error {
err := *e
if e.cause != nil {
err.message = e.cause.Error()
err.args = nil
}
err.args = freezeHackedStringArgs(args)
RedactErrorArg(err.args, e.redactArgsPos)
return SuspendStack(&err)
}

func (e *Error) GenWithStackByCause(args ...any) error {
// GenWithStackByCause generates an error with a stack trace and the same class
// and code, using the cause's error text as a literal message without formatting arguments.
// Only use it as errorTemplate.Wrap(err).GenWithStackByCause().
// To format the template with arguments, use GenWithStackByArgs instead.
func (e *Error) GenWithStackByCause() error {
err := *e
if e.cause != nil {
err.message = e.cause.Error()
err.args = nil
}
err.args = freezeHackedStringArgs(args)
RedactErrorArg(err.args, e.redactArgsPos)
err.fillLineAndFile(1)
return AddStack(&err)
}
Expand Down
80 changes: 18 additions & 62 deletions normalize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,8 @@
func TestGenWithStackByCauseRedaction(t *testing.T) {
previousMode := RedactLogEnabled.Load()
t.Cleanup(func() { RedactLogEnabled.Store(previousMode) })
prototype := Normalize("template %s, public %s", RFCCodeText("Internal:Test"), RedactArgs([]int{0, 5}))
cause := stderrors.New("cause %s, public %s")
wrapped := prototype.Wrap(cause)
prototype := Normalize("unused template", RFCCodeText("Internal:Test"), RedactArgs([]int{0}))
causeTemplate := Normalize("cause %s, public %s, 95%% full, %%1000000[1]d", RFCCodeText("Internal:Cause"), RedactArgs([]int{0}))

for _, tc := range []struct {
mode string
Expand All @@ -256,29 +255,21 @@
} {
t.Run(tc.mode, func(t *testing.T) {
RedactLogEnabled.Store(tc.mode)
origin := []byte("secret‹›")
err := wrapped.GenWithStackByCause(hackedStringArg{raw: origin}, "visible")
fallback := prototype.GenWithStackByCause(hackedStringArg{raw: origin}, "visible")
copy(origin, "modified")
cause := causeTemplate.GenWithStackByArgs("secret‹›", "visible")
err := prototype.Wrap(cause).GenWithStackByCause()
want := "[Internal:Cause]cause " + tc.arg + ", public visible, 95% full, %1000000[1]d"
got := err.(*withStack).error.(*Error)
require.Equal(t, "cause "+tc.arg+", public visible", got.GetMsg())
require.Same(t, cause, got.Unwrap())
require.Equal(t, prototype.ID(), got.ID())
require.True(t, HasStack(err))
require.Contains(t, fmt.Sprintf("%+v", err), "TestGenWithStackByCauseRedaction")
require.EqualError(t, fallback, "[Internal:Test]template "+tc.arg+", public visible")
require.Equal(t, "template %s, public %s", wrapped.message)
require.Empty(t, wrapped.args)
require.Equal(t, want, got.GetMsg())
require.EqualError(t, err, "[Internal:Test]"+want+": "+want)
})
}
}

func TestFastGenWithCauseRedaction(t *testing.T) {
previousMode := RedactLogEnabled.Load()
t.Cleanup(func() { RedactLogEnabled.Store(previousMode) })
prototype := Normalize("template %s, public %s", RFCCodeText("Internal:Test"), RedactArgs([]int{0, 5}))
cause := stderrors.New("cause %s, public %s")
wrapped := prototype.Wrap(cause)
prototype := Normalize("unused template", RFCCodeText("Internal:Test"), RedactArgs([]int{0}))
causeTemplate := Normalize("cause %s, public %s, 95%% full, %%1000000[1]d", RFCCodeText("Internal:Cause"), RedactArgs([]int{0}))

for _, tc := range []struct {
mode string
Expand All @@ -290,21 +281,12 @@
} {
t.Run(tc.mode, func(t *testing.T) {
RedactLogEnabled.Store(tc.mode)
origin := []byte("secret‹›")
err := wrapped.FastGenWithCause(hackedStringArg{raw: origin}, "visible")
fallback := prototype.FastGenWithCause(hackedStringArg{raw: origin}, "visible")
copy(origin, "modified")
cause := causeTemplate.GenWithStackByArgs("secret‹›", "visible")
err := prototype.Wrap(cause).FastGenWithCause()
want := "[Internal:Cause]cause " + tc.arg + ", public visible, 95% full, %1000000[1]d"
got := err.(*withStack).error.(*Error)
require.Equal(t, "cause "+tc.arg+", public visible", got.GetMsg())
require.Same(t, cause, got.Unwrap())
require.Equal(t, prototype.ID(), got.ID())
require.False(t, HasStack(err))
file, line := got.Location()
require.Empty(t, file)
require.Zero(t, line)
require.EqualError(t, fallback, "[Internal:Test]template "+tc.arg+", public visible")
require.Equal(t, "template %s, public %s", wrapped.message)
require.Empty(t, wrapped.args)
require.Equal(t, want, got.GetMsg())
require.EqualError(t, err, "[Internal:Test]"+want+": "+want)
})
}
}
Expand All @@ -324,10 +306,10 @@
{"GenWithStackByArgs", prototype.GenWithStackByArgs},
{"FastGen", func(args ...any) error { return prototype.FastGen(format, args...) }},
{"FastGenByArgs", prototype.FastGenByArgs},
{"GenWithStackByCause", wrapped.GenWithStackByCause},

Check failure on line 309 in normalize_test.go

View workflow job for this annotation

GitHub Actions / test

cannot use wrapped.GenWithStackByCause (value of type func() error) as func(...any) error value in struct literal
{"GenWithStackByCauseFallback", prototype.GenWithStackByCause},

Check failure on line 310 in normalize_test.go

View workflow job for this annotation

GitHub Actions / test

cannot use prototype.GenWithStackByCause (value of type func() error) as func(...any) error value in struct literal
{"FastGenWithCause", wrapped.FastGenWithCause},

Check failure on line 311 in normalize_test.go

View workflow job for this annotation

GitHub Actions / test

cannot use wrapped.FastGenWithCause (value of type func() error) as func(...any) error value in struct literal
{"FastGenWithCauseFallback", prototype.FastGenWithCause},

Check failure on line 312 in normalize_test.go

View workflow job for this annotation

GitHub Actions / test

cannot use prototype.FastGenWithCause (value of type func() error) as func(...any) error value in struct literal
}
argTypes := []struct {
name string
Expand Down Expand Up @@ -384,6 +366,8 @@
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
wrapped := errTest.Wrap(err).GenWithStackByCause()
require.Equal(t, err.Error(), wrapped.(*withStack).error.(*Error).GetMsg())
}

func TestFastGenByArgsFreezeHackedStringArg(t *testing.T) {
Expand All @@ -399,6 +383,8 @@
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
wrapped := errTest.Wrap(err).FastGenWithCause()
require.Equal(t, err.Error(), wrapped.(*withStack).error.(*Error).GetMsg())
}

func TestGenWithStackFreezeHackedStringArg(t *testing.T) {
Expand Down Expand Up @@ -430,33 +416,3 @@
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}

func TestGenWithStackByCauseFreezeHackedStringArg(t *testing.T) {
errTest := Normalize("Incorrect time value: '%s'", RFCCodeText("Internal:Test"))

origin := []byte("120120519090607")
arg := hackedStringArg{raw: origin}
err := errTest.GenWithStackByCause(arg)

copy(origin, "1 1:1:1.0000027")
got := err.(*withStack).error.(*Error).GetMsg()
want := "Incorrect time value: '120120519090607'"
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}

func TestFastGenWithCauseFreezeHackedStringArg(t *testing.T) {
errTest := Normalize("Incorrect time value: '%s'", RFCCodeText("Internal:Test"))

origin := []byte("120120519090607")
arg := hackedStringArg{raw: origin}
err := errTest.FastGenWithCause(arg)

copy(origin, "1 1:1:1.0000027")
got := err.(*withStack).error.(*Error).GetMsg()
want := "Incorrect time value: '120120519090607'"
if got != want {
t.Fatalf("message changed after source bytes mutated, got %q, want %q", got, want)
}
}
Loading