-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
82 lines (71 loc) · 1.83 KB
/
json.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"encoding/json"
"fmt"
"github.com/aisbergg/go-bruh/pkg/bruh"
)
func main() {
err := foo()
ftdErr := bruh.ToCustomString(err, FormatJSON)
fmt.Println(ftdErr)
}
// -----------------------------------------------------------------------------
// Custom error formatter
// -----------------------------------------------------------------------------
type ErrorStruct struct {
Message string `json:"message"`
Stack []Location `json:"stack"`
}
type Location struct {
Name string `json:"name"`
File string `json:"file"`
Line int `json:"line"`
ProgramCounter uintptr `json:"pc"`
}
func FormatJSON(upkErr bruh.UnpackedError) string {
// convert unpacked error to a list of ErrorStruct
errStructs := make([]ErrorStruct, len(upkErr))
for i, err := range upkErr {
stack := make([]Location, len(err.Stack))
for j, frame := range err.Stack {
stack[j] = Location{
Name: frame.Name,
File: frame.File,
Line: frame.Line,
ProgramCounter: frame.ProgramCounter2,
}
}
errStructs[i] = ErrorStruct{
Message: err.Msg,
Stack: stack,
}
}
// serialize to JSON
serialized, err := json.MarshalIndent(errStructs, "", " ")
if err != nil {
panic(err)
}
fmt.Println("json: ", string(serialized))
return string(serialized)
}
// -----------------------------------------------------------------------------
// Just some functions that return errors
// -----------------------------------------------------------------------------
func foo() error {
err := bar()
if err != nil {
return bruh.Wrapf(err, "foo: failed to read config file")
}
return nil
}
func bar() error {
err := baz()
if err != nil {
return bruh.Wrapf(err, "bar: failed to parse")
}
return nil
}
func baz() error {
// external error
return fmt.Errorf("oh no")
}