liuhaijun e94826ce29 add server
Change-Id: I0760f17f6a01c0121b59fcbfafc666032dbc30af
2024-09-19 09:44:15 +00:00

41 lines
1.3 KiB
Go
Raw 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 (
"errors"
"fmt"
"git.inspur.com/sbg-jszt/cfn/cfn-schedule/config"
e "git.inspur.com/sbg-jszt/cfn/cfn-schedule/internal/pkg/errors"
response2 "git.inspur.com/sbg-jszt/cfn/cfn-schedule/internal/pkg/response"
"git.inspur.com/sbg-jszt/cfn/cfn-schedule/pkg/log"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
// CustomRecovery 自定义错误 (panic) 拦截中间件、对可能发生的错误进行拦截、统一记录
func CustomRecovery() gin.HandlerFunc {
DefaultErrorWriter := &PanicExceptionRecord{}
return gin.RecoveryWithWriter(DefaultErrorWriter, func(c *gin.Context, err interface{}) {
// 这里针对发生的panic等异常进行统一响应即
// 这里针对发生的panic等异常进行统一响应即
errStr := ""
if config.Config.Debug == true {
errStr = fmt.Sprintf("%v", err)
}
response2.Resp().SetHttpCode(http.StatusInternalServerError).FailCode(c, e.ServerError, errStr)
})
}
// PanicExceptionRecord panic等异常记录
type PanicExceptionRecord struct{}
func (p *PanicExceptionRecord) Write(b []byte) (n int, err error) {
s1 := "An error occurred in the server's internal code"
var build strings.Builder
build.WriteString(s1)
build.Write(b)
errStr := build.String()
log.Error(errStr)
return len(errStr), errors.New(errStr)
}