forked from omriharel/deej
-
Notifications
You must be signed in to change notification settings - Fork 0
/
panic.go
68 lines (55 loc) · 1.81 KB
/
panic.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
package deej
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime/debug"
"time"
"github.com/omriharel/deej/util"
)
const (
crashlogFilename = "deej-crash-%s.log"
crashlogTimestampFormat = "2006.01.02-15.04.05"
crashMessage = `-----------------------------------------------------------------
deej crashlog
-----------------------------------------------------------------
Unfortunately, deej has crashed. This really shouldn't happen!
If you've just encountered this, please contact @omriharel and attach this error log.
You can also join the deej Discord server at https://discord.gg/nf88NJu.
-----------------------------------------------------------------
Time: %s
Panic occurred: %s
Stack trace:
%s
-----------------------------------------------------------------
`
)
func (d *Deej) recoverFromPanic() {
r := recover()
if r == nil {
return
}
// if we got here, we're recovering from a panic!
now := time.Now()
// that would suck
if err := util.EnsureDirExists(logDirectory); err != nil {
panic(fmt.Errorf("ensure crashlog dir exists: %w", err))
}
crashlogBytes := bytes.NewBufferString(fmt.Sprintf(crashMessage, now.Format(crashlogTimestampFormat), r, debug.Stack()))
crashlogPath := filepath.Join(logDirectory, fmt.Sprintf(crashlogFilename, now.Format(crashlogTimestampFormat)))
// that would REALLY suck
if err := ioutil.WriteFile(crashlogPath, crashlogBytes.Bytes(), os.ModePerm); err != nil {
panic(fmt.Errorf("can't even write the crashlog file contents: %w", err))
}
d.logger.Errorw("Encountered and logged panic, crashing",
"crashlogPath", crashlogPath,
"error", r)
d.notifier.Notify("Unexpected crash occurred...",
fmt.Sprintf("More details in %s", crashlogPath))
// bye :(
d.signalStop()
d.logger.Errorw("Quitting", "exitCode", 1)
os.Exit(1)
}