go fiber: 抛出自定义异常

一,代码:

1,自定义错误类:

package config

import (
    "fmt"
)
//定义错误代码和错误信息
type MyError struct {
    Code    int
    Msg     string
}
//需要定义通用的Error()方法
func (e MyError) Error() string {
    return fmt.Sprintf("Code: %d,Msg: %s",e.Code, e.Msg)
}

2,代码中抛出异常

package business

import ("industry/config")

//得到多个用户,按分页返回
func GetUserList(page int ,pageSize int) (string,error) {

    err := config.MyError{Code: 100, Msg: "遇到错误抛出自定义异常1234"}
    panic(&err)

    return "1,2,3",nil
}

3, middleware中捕获异常,按类型进行处理

package middleware

import (
	"fmt"
	"runtime/debug"
    "time"
	"github.com/gofiber/fiber/v2"
    "industry/config"
)


func NewRecover(c *fiber.Ctx) (err error) { //nolint:nonamedreturns // Uses recover() to overwrite the error

		// Catch panics
		defer func() {

			if r := recover(); r != nil {
               //如果是自定义异常时,则不需写日志
               if err1, ok1 := r.(*config.MyError); ok1 {
                   fmt.Println("----------找到了自定义错误:")
                   fmt.Println(err1)
                   fmt.Println("错误代码:"+fmt.Sprintf("%d", err1.Code))
                   fmt.Println("错误信息:"+err1.Msg)
                   //接收到用户自定义错误,不再写到日志中
                   err = err1

               } else {

                timeStr:=time.Now().Format("2006-01-02 15:04:05")
                //得到时间,ip地址,请求的地址,参数,user-agent,
                fullURL := c.OriginalURL()
                clientIP := c.IP()
                method := c.Method() // 获取请求方法
                userAgent := c.Get("User-Agent")
                // 获取所有查询参数
                queryParams := fmt.Sprintf("%v",c.Queries())
                fmt.Println("Query Params:", queryParams)
                //写到错误日志中
        filename:="/data/logs/gologs/exception-" + time.Now().Format("2006-01-02") + ".log"
        content:="["+timeStr+"] "+r.(error).Error()+"\n"+clientIP+" "+method+" "+fullURL+" "+userAgent+"\n"+queryParams+"\n"+string(debug.Stack())+"\n"
        config.GlobalWriteFile(filename,content)

				var ok bool
				if err, ok = r.(error); !ok {
					// Set error that will call the global error handler
					err = fmt.Errorf("%v", r)
				}
              }
			}
		}()

		// Return err if exist, else move to next handler
		return c.Next()
}

4, 返回错误信息时也按类型判断后处理

routes.go

package routes

import (
	"github.com/gofiber/fiber/v2"
	"industry/controller"
    "industry/middleware"
    "industry/config"
    "fmt"
)



func SetupRoutes() *fiber.App {

    app := fiber.New(fiber.Config{
		ErrorHandler: func(c *fiber.Ctx, err error) error {
			// 发送自定义错误页面
            // 如果是自定义错误,不再统一按500返回
            if err1,ok1:=err.(*config.MyError);ok1 {
                fmt.Println(err1)
                fmt.Println("route:错误是自定义异常")
                return c.SendString("内部错误代码:"+fmt.Sprintf("%d", err1.Code)+",错误信息:"+err1.Msg)
            } else {
                fmt.Println("route:错误不是自定义异常")
                return c.SendString("内部错误:500,"+err.Error())
            }
		},
	})



    app.Use(middleware.NewRecover)

    app.Use(middleware.ApiSign)

	//用户模块
	userController := controller.NewUserController()
	user := app.Group("/user")
	user.Get("/info", userController.GetUser)
	user.Post("/", userController.CreateUser)
    user.Get("/list", userController.ListUser)

	//文章模块
	articleController := controller.NewArticleController()
	article := app.Group("/article")
	article.Get("/info", articleController.GetArticle)
	article.Post("/add", articleController.CreateArticle)
    article.Get("/list", articleController.ListArticle)

    return app
}

二,测试效果:

 

 

posted @ 2024-11-15 11:28  刘宏缔的架构森林  阅读(25)  评论(0编辑  收藏  举报