补充Gin Revoery异常处理场景

This commit is contained in:
yumaojun03 2025-05-11 17:54:03 +08:00
parent 43f675d736
commit 665fde6609
4 changed files with 35 additions and 2 deletions

View File

@ -86,3 +86,17 @@ if exception.IsApiException(err, exception.CODE_NOT_FOUND) {
// 异常处理逻辑 // 异常处理逻辑
} }
``` ```
## Gin Revovery 结合
```go
// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
// 自定义异常处理机制
func Recovery() gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, err any) {
// 非业务异常
c.JSON(500, NewApiException(500, fmt.Sprintf("%#v", err)))
c.Abort()
})
}
```

View File

@ -0,0 +1,17 @@
package exception
import (
"fmt"
"github.com/gin-gonic/gin"
)
// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
// 自定义异常处理机制
func Recovery() gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, err any) {
// 非业务异常
c.JSON(500, NewApiException(500, fmt.Sprintf("%#v", err)))
c.Abort()
})
}

View File

@ -5,6 +5,7 @@ import (
"os" "os"
"122.51.31.227/go-course/go18/book/v3/config" "122.51.31.227/go-course/go18/book/v3/config"
"122.51.31.227/go-course/go18/book/v3/exception"
"122.51.31.227/go-course/go18/book/v3/handlers" "122.51.31.227/go-course/go18/book/v3/handlers"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -17,7 +18,8 @@ func main() {
} }
config.LoadConfigFromYaml(path) config.LoadConfigFromYaml(path)
server := gin.Default() server := gin.New()
server.Use(gin.Logger(), exception.Recovery())
handlers.Book.Registry(server) handlers.Book.Registry(server)

View File

@ -8,7 +8,7 @@ import (
) )
func main() { func main() {
server := gin.Default() server := gin.New()
server.GET("/hello", func(ctx *gin.Context) { server.GET("/hello", func(ctx *gin.Context) {
ctx.String(200, "Gin Hello World!") ctx.String(200, "Gin Hello World!")