Skip to content

Commit 42b9692

Browse files
authored
Merge pull request #4 from zignd/skip-nil-data-json
Skip nil data from serialized JSON
2 parents 4e87c2e + a4c5c26 commit 42b9692

File tree

4 files changed

+51
-13
lines changed

4 files changed

+51
-13
lines changed

README.md

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ For a better understanding of the features provided by the package check the doc
2222

2323
# Quick demo
2424

25-
There's an example at `examples/example1/example1.go` that shows how to use the package. Here's the code for the example:
25+
There's an example at `examples/example1/example1.go` that shows how to use the package.
26+
27+
<details><summary>Here's the code for the example:</summary>
2628

2729
```go
2830
package main
@@ -78,11 +80,11 @@ func open() error {
7880
func main() {
7981
if err := createTransaction("tx_123456"); err != nil {
8082
b, _ := json.MarshalIndent(err, "", " ")
81-
fmt.Println("Error logged as a JSON structure using the JSON.MarshalIndent:")
83+
fmt.Println("Error logged as a JSON structure using the json.MarshalIndent:")
8284
fmt.Printf("%s\n", b)
8385

8486
b, _ = json.Marshal(err)
85-
fmt.Println("\nError logged as a JSON structure using the JSON.Marshal:")
87+
fmt.Println("\nError logged as a JSON structure using the json.Marshal:")
8688
fmt.Printf("%s\n", b)
8789

8890
fmt.Println("\nError logged using the s format specifier:")
@@ -94,11 +96,13 @@ func main() {
9496
}
9597
```
9698

97-
Here's the execution of the example:
99+
</details>
100+
101+
<details><summary>Here's the execution of the example:</summary>
98102

99103
```
100-
$ go run examples/example1/example1.go
101-
Error logged as a JSON structure using the JSON.MarshalIndent:
104+
$ go run examples/example1/example1.go
105+
Error logged as a JSON structure using the json.MarshalIndent:
102106
[
103107
{
104108
"data": {
@@ -160,7 +164,7 @@ Error logged as a JSON structure using the JSON.MarshalIndent:
160164
}
161165
]
162166
163-
Error logged as a JSON structure using the JSON.Marshal:
167+
Error logged as a JSON structure using the json.Marshal:
164168
[{"data":{"transactionId":"tx_123456","userId":"67890"},"message":"failed to complete the transaction on bank_123456","stack":["main.createTransaction @ /root/hack/errors/examples/example1/example1.go:13","main.main @ /root/hack/errors/examples/example1/example1.go:52","runtime/internal/atomic.(*Uint32).Load @ /root/go/version/go1.21.0/src/runtime/internal/atomic/types.go:194","runtime.goexit @ /root/go/version/go1.21.0/src/runtime/asm_amd64.s:1651"]},{"data":{"operation":"update","tableName":"transactions"},"message":"failed to update the database","stack":["main.updateDatabase @ /root/hack/errors/examples/example1/example1.go:24","main.createTransaction @ /root/hack/errors/examples/example1/example1.go:12","main.main @ /root/hack/errors/examples/example1/example1.go:52","runtime/internal/atomic.(*Uint32).Load @ /root/go/version/go1.21.0/src/runtime/internal/atomic/types.go:194","runtime.goexit @ /root/go/version/go1.21.0/src/runtime/asm_amd64.s:1651"]},{"data":{"server":"db-server-01","timeoutSeconds":30},"message":"connection timeout","stack":["main.createConnection @ /root/hack/errors/examples/example1/example1.go:35","main.updateDatabase @ /root/hack/errors/examples/example1/example1.go:23","main.createTransaction @ /root/hack/errors/examples/example1/example1.go:12","main.main @ /root/hack/errors/examples/example1/example1.go:52","runtime/internal/atomic.(*Uint32).Load @ /root/go/version/go1.21.0/src/runtime/internal/atomic/types.go:194","runtime.goexit @ /root/go/version/go1.21.0/src/runtime/asm_amd64.s:1651"]},{"data":{"network":"internal","severity":"high"},"message":"network instability detected","stack":["main.open @ /root/hack/errors/examples/example1/example1.go:45","main.createConnection @ /root/hack/errors/examples/example1/example1.go:34","main.updateDatabase @ /root/hack/errors/examples/example1/example1.go:23","main.createTransaction @ /root/hack/errors/examples/example1/example1.go:12","main.main @ /root/hack/errors/examples/example1/example1.go:52","runtime/internal/atomic.(*Uint32).Load @ /root/go/version/go1.21.0/src/runtime/internal/atomic/types.go:194","runtime.goexit @ /root/go/version/go1.21.0/src/runtime/asm_amd64.s:1651"]}]
165169
166170
Error logged using the s format specifier:
@@ -170,8 +174,8 @@ Error logged using the +v format specifier:
170174
message:
171175
"failed to complete the transaction on bank_123456"
172176
data:
173-
transactionId: tx_123456
174177
userId: 67890
178+
transactionId: tx_123456
175179
stack:
176180
main.createTransaction @ /root/hack/errors/examples/example1/example1.go:13
177181
main.main @ /root/hack/errors/examples/example1/example1.go:52
@@ -216,4 +220,6 @@ cause:
216220
main.main @ /root/hack/errors/examples/example1/example1.go:52
217221
runtime/internal/atomic.(*Uint32).Load @ /root/go/version/go1.21.0/src/runtime/internal/atomic/types.go:194
218222
runtime.goexit @ /root/go/version/go1.21.0/src/runtime/asm_amd64.s:1651
219-
```
223+
```
224+
225+
</details>

convertion.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ func toMapAndCause(err error) (map[string]any, error) {
3030

3131
if e, ok := err.(*Err); ok {
3232
errMap["message"] = e.Message
33-
errMap["data"] = e.Data
33+
if e.Data != nil {
34+
errMap["data"] = e.Data
35+
}
3436
errMap["stack"] = e.Stack
3537
errCause = e.Cause
3638
} else {

error_test.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ func TestJSONMarshaling(t *testing.T) {
1010
t.Run("when marshaling a nested chain of errors.Err errors, should marshal the full chain", func(t *testing.T) {
1111
err1 := New("context timeout")
1212
err2 := Wrap(err1, "failed to connect to the database")
13-
err3 := Wrap(err2, "failed to start the server")
13+
err3 := Wrapd(err2, Data{
14+
"server": "db-server-01",
15+
}, "failed to start the server")
1416

1517
b, err := json.MarshalIndent(err3, "", " ")
1618
if err != nil {
@@ -27,17 +29,45 @@ func TestJSONMarshaling(t *testing.T) {
2729
t.Fatalf("unexpected number of errors, got %d, expected %d", len(errs), 3)
2830
}
2931

32+
// testing err3
33+
3034
if fmt.Sprint(errs[0]["message"]) != err3.(*Err).Message {
3135
t.Errorf("unexpected error message, got %q, expected %q", errs[0]["message"], err3.(*Err).Message)
3236
}
3337

38+
dataErr3, ok := errs[0]["data"]
39+
if !ok {
40+
t.Errorf("unexpected data, got undefined key, expected %v", err3.(*Err).Data)
41+
}
42+
43+
b1, err := json.Marshal(dataErr3)
44+
if err != nil {
45+
t.Fatalf("unexpected error: %v", err)
46+
}
47+
b2, err := json.Marshal(err3.(*Err).Data)
48+
if err != nil {
49+
t.Fatalf("unexpected error: %v", err)
50+
}
51+
52+
if string(b1) != string(b2) {
53+
t.Errorf("unexpected data, got %s, expected %s", b1, b2)
54+
}
55+
56+
// testing err2
57+
3458
if fmt.Sprint(errs[1]["message"]) != err2.(*Err).Message {
3559
t.Errorf("unexpected error message, got %q, expected %q", errs[1]["message"], err2.(*Err).Message)
3660
}
3761

62+
// testing err1
63+
3864
if fmt.Sprint(errs[2]["message"]) != err1.(*Err).Message {
3965
t.Errorf("unexpected error message, got %q, expected %q", errs[2]["message"], err1.(*Err).Message)
4066
}
67+
68+
if _, ok := errs[2]["data"]; ok {
69+
t.Errorf("unexpected data, got %v, expected undefined key", errs[0]["data"])
70+
}
4171
})
4272

4373
t.Run("when marshaling a chain of errors.Err and standard errors, should marshal the full chain", func(t *testing.T) {

examples/example1/example1.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@ func open() error {
5151
func main() {
5252
if err := createTransaction("tx_123456"); err != nil {
5353
b, _ := json.MarshalIndent(err, "", " ")
54-
fmt.Println("Error logged as a JSON structure using the JSON.MarshalIndent:")
54+
fmt.Println("Error logged as a JSON structure using the json.MarshalIndent:")
5555
fmt.Printf("%s\n", b)
5656

5757
b, _ = json.Marshal(err)
58-
fmt.Println("\nError logged as a JSON structure using the JSON.Marshal:")
58+
fmt.Println("\nError logged as a JSON structure using the json.Marshal:")
5959
fmt.Printf("%s\n", b)
6060

6161
fmt.Println("\nError logged using the s format specifier:")

0 commit comments

Comments
 (0)