Skip to content

Commit

Permalink
feat: add panic recover middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Dec 10, 2023
1 parent 4c5feee commit 2a70744
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 26 additions & 0 deletions middleware/recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package middleware

import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"one-api/common"
)

func RelayPanicRecover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
common.SysError(fmt.Sprintf("panic detected: %v", err))
c.JSON(http.StatusInternalServerError, gin.H{
"error": gin.H{
"message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/songquanpeng/one-api", err),
"type": "one_api_panic",
},
})
c.Abort()
}
}()
c.Next()
}
}
2 changes: 1 addition & 1 deletion router/relay-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func SetRelayRouter(router *gin.Engine) {
modelsRouter.GET("/:model", controller.RetrieveModel)
}
relayV1Router := router.Group("/v1")
relayV1Router.Use(middleware.TokenAuth(), middleware.Distribute())
relayV1Router.Use(middleware.RelayPanicRecover(), middleware.TokenAuth(), middleware.Distribute())
{
relayV1Router.POST("/completions", controller.Relay)
relayV1Router.POST("/chat/completions", controller.Relay)
Expand Down

0 comments on commit 2a70744

Please sign in to comment.