Skip to content

Commit ae7e336

Browse files
add; serializable method that supports debug flag to hide the underlying cause of the error
1 parent bf0b0fe commit ae7e336

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-0
lines changed

debug.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// +build debug
2+
3+
package errors
4+
5+
// Return a serializable error struct that cna omit exposing internal errors as an option in release mode
6+
func Serializable(err error) *Error {
7+
return Unwrap(err)
8+
}

debug_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// +build debug
2+
3+
package errors
4+
5+
import (
6+
"testing"
7+
)
8+
9+
func TestSerializableInDebug(t *testing.T) {
10+
cause := New("causal error")
11+
const msg = "external error message for the client"
12+
err := New(msg, Permission, cause)
13+
got := testJSONRoundTrip(Serializable(err)).(*Error)
14+
if got.msg != msg {
15+
t.Errorf("Serializable(); got msg = %v, want %v", got.msg, msg)
16+
}
17+
if got.cause == nil || got.cause.Error() != cause.Error() {
18+
t.Errorf("Serializable(); got cause.Error() = %v, want %v", got.cause.Error(), cause.Error())
19+
}
20+
if got.kind != Permission {
21+
t.Errorf("Serializable(); got kind = %v, want %v", got.kind, Permission)
22+
}
23+
24+
}

release.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// +build !debug
2+
3+
package errors
4+
5+
// Serializable returns a serializable error struct that cna omit exposing internal errors as an option in release mode
6+
func Serializable(err error) *Error {
7+
e := Unwrap(err)
8+
e.cause = nil
9+
return e
10+
}

release_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// +build !debug
2+
3+
package errors
4+
5+
import (
6+
"testing"
7+
)
8+
9+
func TestSerializableInRelease(t *testing.T) {
10+
cause := New("causal error")
11+
const msg = "external error message for the client"
12+
err := New(msg, Permission, cause)
13+
got := testJSONRoundTrip(Serializable(err)).(*Error)
14+
if got.msg != msg {
15+
t.Errorf("Serializable(); got msg = %v, want %v", got.msg, msg)
16+
}
17+
if got.cause != nil {
18+
t.Errorf("Serializable(); got cause = %v, want %v", got.cause, nil)
19+
}
20+
if got.kind != Permission {
21+
t.Errorf("Serializable(); got kind = %v, want %v", got.kind, Permission)
22+
}
23+
}

0 commit comments

Comments
 (0)