53 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			53 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
package core
 | 
						|
 | 
						|
import (
 | 
						|
	"fmt"
 | 
						|
	"git.echol.cn/loser/logger/log"
 | 
						|
	"github.com/gin-gonic/gin"
 | 
						|
	"net"
 | 
						|
	"net/http"
 | 
						|
	"os"
 | 
						|
	"strings"
 | 
						|
)
 | 
						|
 | 
						|
// NoMethodHandler 请求方式不对
 | 
						|
func NoMethodHandler() gin.HandlerFunc {
 | 
						|
	return func(ctx *gin.Context) {
 | 
						|
		R(ctx).FailWithMessageAndCode(fmt.Sprintf("不支持%v请求", ctx.Request.Method), http.StatusMethodNotAllowed)
 | 
						|
		ctx.Abort()
 | 
						|
	}
 | 
						|
}
 | 
						|
 | 
						|
// NoRouteHandler 404异常处理
 | 
						|
func NoRouteHandler() gin.HandlerFunc {
 | 
						|
	return func(ctx *gin.Context) {
 | 
						|
		R(ctx).FailWithMessageAndCode("请求接口不存在", http.StatusNotFound)
 | 
						|
		ctx.Abort()
 | 
						|
	}
 | 
						|
}
 | 
						|
 | 
						|
// Recovery Panic捕获
 | 
						|
func Recovery() gin.HandlerFunc {
 | 
						|
	return func(ctx *gin.Context) {
 | 
						|
		defer func() {
 | 
						|
			if err := recover(); err != nil {
 | 
						|
				log.Errorf("系统错误: %v", err)
 | 
						|
				var brokenPipe bool
 | 
						|
				if ne, ok := err.(*net.OpError); ok {
 | 
						|
					if se, ok := ne.Err.(*os.SyscallError); ok {
 | 
						|
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
 | 
						|
							brokenPipe = true
 | 
						|
						}
 | 
						|
					}
 | 
						|
				}
 | 
						|
				if brokenPipe {
 | 
						|
					log.Errorf("%s", err)
 | 
						|
				}
 | 
						|
				R(ctx).FailWithMessage("服务器异常,请联系管理员")
 | 
						|
				ctx.Abort()
 | 
						|
			}
 | 
						|
		}()
 | 
						|
		ctx.Next()
 | 
						|
	}
 | 
						|
}
 |