Skip to content

Commit

Permalink
refactor(recovery): smart error comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
zeek0x committed Jan 18, 2025
1 parent 3f818c3 commit d569590
Showing 1 changed file with 10 additions and 16 deletions.
26 changes: 10 additions & 16 deletions recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import (
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"os"
"runtime"
"strings"
"syscall"
"time"
)

Expand Down Expand Up @@ -55,19 +55,13 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
}
return func(c *Context) {
defer func() {
if err := recover(); err != nil {
if rec := recover(); rec != nil {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
var se *os.SyscallError
if errors.As(ne, &se) {
seStr := strings.ToLower(se.Error())
if strings.Contains(seStr, "broken pipe") ||
strings.Contains(seStr, "connection reset by peer") {
brokenPipe = true
}
}
var isBrokenPipeOrConnReset bool
err, ok := rec.(error)
if ok {
isBrokenPipeOrConnReset = errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET)
}
if logger != nil {
stack := stack(3)
Expand All @@ -80,7 +74,7 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
}
}
headersToStr := strings.Join(headers, "\r\n")
if brokenPipe {
if isBrokenPipeOrConnReset {
logger.Printf("%s\n%s%s", err, headersToStr, reset)
} else if IsDebugging() {
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
Expand All @@ -90,12 +84,12 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
timeFormat(time.Now()), err, stack, reset)
}
}
if brokenPipe {
if isBrokenPipeOrConnReset {
// If the connection is dead, we can't write a status to it.
c.Error(err.(error)) //nolint: errcheck
c.Error(err) //nolint: errcheck
c.Abort()
} else {
handle(c, err)
handle(c, rec)
}
}
}()
Expand Down

0 comments on commit d569590

Please sign in to comment.