wails-app-dock/pkg/server/middleware/error.go
2024-02-17 21:45:43 +08:00

40 lines
832 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
"runtime/debug"
"skapp/pkg/logger"
"skapp/pkg/utils/errorx"
)
// ErrorHandler
// gin 全局异常处理
func ErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
err := parseError(r)
//打印错误堆栈信息
logger.Log.Error(err)
debug.PrintStack()
//封装通用JSON返回
c.JSON(http.StatusOK, errorx.NewDefaultError(err))
//终止后续接口调用不加的话recover到异常后还会继续执行接口里后续代码
c.Abort()
}
}()
//加载完 defer recover继续后续的插件及代码执行
c.Next()
}
}
func parseError(r interface{}) string {
switch v := r.(type) {
case error:
return v.Error()
default:
return r.(string)
}
}