Skip to content

Commit

Permalink
Add reporting and recovery for panics
Browse files Browse the repository at this point in the history
  • Loading branch information
haroldcampbell committed May 10, 2021
1 parent 8c4138e commit 20c6e95
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions serverutils/actionstatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package serverutils

import (
"encoding/json"
"fmt"
"go_utils/utils"
"net/http"
"runtime"
"strings"
)

// ActionStatus return status for handlers
Expand Down Expand Up @@ -66,3 +69,40 @@ func WriteErrorMessage(w http.ResponseWriter, errMessage string) {
b, _ := json.Marshal(ErrorResponse{DidFail: true, ErrorMessage: errMessage})
w.Write(b)
}

// https://gist.github.com/swdunlop/9629168
func identifyPanic() string {
var name, file string
var line int
var pc [16]uintptr

n := runtime.Callers(3, pc[:])
for _, pc := range pc[:n] {
fn := runtime.FuncForPC(pc)
if fn == nil {
continue
}
file, line = fn.FileLine(pc)
name = fn.Name()
if !strings.HasPrefix(name, "runtime.") {
break
}
}

switch {
case name != "":
return fmt.Sprintf("%v:%v", name, line)
case file != "":
return fmt.Sprintf("%v:%v", file, line)
}

return fmt.Sprintf("pc:%x", pc)
}

func RecoverPanic(src string) {
r := recover()
if r == nil {
return
}
utils.Error(src, "PANIC:[%v] at %s", r, identifyPanic())
}

0 comments on commit 20c6e95

Please sign in to comment.