ai-gateway/middleware/recover.go

34 lines
1015 B
Go
Raw Normal View History

2023-12-10 11:53:33 +00:00
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
2024-03-10 15:59:35 +00:00
"github.com/songquanpeng/one-api/common"
2024-01-28 11:38:58 +00:00
"github.com/songquanpeng/one-api/common/logger"
2023-12-10 11:53:33 +00:00
"net/http"
2023-12-24 10:54:32 +00:00
"runtime/debug"
2023-12-10 11:53:33 +00:00
)
func RelayPanicRecover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
2024-03-10 15:59:35 +00:00
ctx := c.Request.Context()
logger.Errorf(ctx, fmt.Sprintf("panic detected: %v", err))
logger.Errorf(ctx, fmt.Sprintf("stacktrace from panic: %s", string(debug.Stack())))
logger.Errorf(ctx, fmt.Sprintf("request: %s %s", c.Request.Method, c.Request.URL.Path))
body, _ := common.GetRequestBody(c)
logger.Errorf(ctx, fmt.Sprintf("request body: %s", string(body)))
2023-12-10 11:53:33 +00:00
c.JSON(http.StatusInternalServerError, gin.H{
"error": gin.H{
2024-03-10 15:59:35 +00:00
"message": fmt.Sprintf("Panic detected, error: %v. Please submit an issue with the related log here: https://github.com/songquanpeng/one-api", err),
2023-12-10 11:53:33 +00:00
"type": "one_api_panic",
},
})
c.Abort()
}
}()
c.Next()
}
}