feat 添加错误处理,统一返回结构
All checks were successful
Build image / build (push) Successful in 41s

This commit is contained in:
timerzz 2024-07-02 17:50:49 +08:00
parent a63c9fe295
commit 84ea5529d2

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/cors"
@ -23,6 +24,26 @@ func main() {
s := &Service{cli: cli}
app := fiber.New(fiber.Config{
StructValidator: &structValidator{validate: validator.New()},
ErrorHandler: func(ctx fiber.Ctx, err error) error {
// Status code defaults to 500
code := fiber.StatusInternalServerError
// Retrieve the custom status code if it's a *fiber.Error
var e *fiber.Error
if errors.As(err, &e) {
code = e.Code
}
// Send custom error page
err = ctx.Status(code).JSON(fiber.Map{
"data": "",
"code": code,
"msg": err.Error(),
})
// Return from handler
return nil
},
})
app.Use(recover.New(), cors.New())