/
panic_handler.go
69 lines (55 loc) · 1.59 KB
/
panic_handler.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
package cli
import (
"fmt"
"os"
"runtime"
"strings"
"github.com/wulonghui/cli/terminal"
)
func displayCrashDialog(err interface{}, commandArgs string, stackTrace string) {
if err != nil && err != terminal.QuietPanic {
switch err := err.(type) {
case error:
printCrashDialog(err.Error(), commandArgs, stackTrace)
case string:
printCrashDialog(err, commandArgs, stackTrace)
default:
printCrashDialog("An unexpected type of error", commandArgs, stackTrace)
}
}
}
func crashDialog(errorMessage string, commandArgs string, stackTrace string) string {
formattedString := `
Something completely unexpected happened. This is a bug.
Tell us that you ran this command:
%s
and that this error occurred:
%s
and this stack trace:
%s
`
return fmt.Sprintf(formattedString, commandArgs, errorMessage, stackTrace)
}
func printCrashDialog(errorMessage string, commandArgs string, stackTrace string) {
terminal.Say(crashDialog(errorMessage, commandArgs, stackTrace))
}
func generateBacktrace() string {
stackByteCount := 0
STACK_SIZE_LIMIT := 1024 * 1024
var bytes []byte
for stackSize := 1024; (stackByteCount == 0 || stackByteCount == stackSize) && stackSize < STACK_SIZE_LIMIT; stackSize = 2 * stackSize {
bytes = make([]byte, stackSize)
stackByteCount = runtime.Stack(bytes, true)
}
stackTrace := "\t" + strings.Replace(string(bytes), "\n", "\n\t", -1)
return stackTrace
}
func handlePanics() {
commandArgs := strings.Join(os.Args, " ")
stackTrace := generateBacktrace()
err := recover()
displayCrashDialog(err, commandArgs, stackTrace)
if err != nil {
os.Exit(1)
}
}