File size: 2,222 Bytes
bf9e111
 
 
 
 
 
 
 
 
 
 
2e6b65c
 
bf9e111
 
 
 
 
 
 
 
 
2e6b65c
bf9e111
 
 
 
 
 
 
 
2e6b65c
bf9e111
 
 
 
2e6b65c
bf9e111
 
2e6b65c
bf9e111
 
 
 
 
 
 
 
 
 
 
 
 
 
2e6b65c
bf9e111
 
 
 
 
2e6b65c
bf9e111
 
2e6b65c
bf9e111
 
2e6b65c
bf9e111
 
 
 
 
 
 
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
// Package middleware provides HTTP middleware components for the CLI Proxy API server.
// This file contains panic recovery middleware for graceful error handling.
package middleware

import (
	"fmt"
	"net/http"
	"runtime/debug"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"github.com/router-for-me/CLIProxyAPI/v6/internal/application/dto"
)

// RecoveryMiddleware creates a Gin middleware that recovers from panics
// and returns a graceful error response instead of crashing the server.
// It logs the panic details including stack trace for debugging.
func RecoveryMiddleware(logger *logrus.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if r := recover(); r != nil {
				requestID := c.GetString("request_id")
				// Log the panic with stack trace if logger is available
				if logger != nil {
					logger.WithFields(logrus.Fields{
						"panic":      r,
						"stacktrace": string(debug.Stack()),
						"path":       c.Request.URL.Path,
						"method":     c.Request.Method,
						"client_ip":  c.ClientIP(),
						"request_id": requestID,
					}).Error("Panic recovered in HTTP handler")
				}

				// Return graceful error response
				c.AbortWithStatusJSON(http.StatusInternalServerError, dto.InternalErrorResponse{
					Success:   false,
					RequestID: requestID,
					Error:     "An internal server error occurred",
				})
			}
		}()

		c.Next()
	}
}

// SafeHandler wraps a handler function to catch panics at the handler level.
// This provides an additional layer of protection for critical endpoints.
func SafeHandler(handler gin.HandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if r := recover(); r != nil {
				requestID := c.GetString("request_id")
				// Log the panic
				logrus.WithFields(logrus.Fields{
					"panic":      fmt.Sprintf("%v", r),
					"path":       c.Request.URL.Path,
					"method":     c.Request.Method,
					"request_id": requestID,
				}).Error("Panic recovered in handler")

				c.AbortWithStatusJSON(http.StatusInternalServerError, dto.InternalErrorResponse{
					Success:   false,
					RequestID: requestID,
					Error:     "An internal server error occurred",
				})
			}
		}()

		handler(c)
	}
}