From 2aadccd5b87051a8de1d89028d89a101b70b0db5 Mon Sep 17 00:00:00 2001 From: hupeh Date: Thu, 12 Oct 2023 17:13:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86?= =?UTF-8?q?=E4=B8=8E=20rsp=20=E7=9A=84=E8=BF=94=E5=9B=9E=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/init.go | 7 +------ pkg/rsp/error_handler.go | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 pkg/rsp/error_handler.go diff --git a/internal/init.go b/internal/init.go index 4ac4fcb..2363a91 100644 --- a/internal/init.go +++ b/internal/init.go @@ -4,7 +4,6 @@ import ( "errors" "github.com/labstack/echo/v4" "gorm.io/gorm" - "net/http" "sorbet/internal/entities" "sorbet/internal/middleware" "sorbet/internal/repositories" @@ -57,11 +56,7 @@ func Start() error { e := echo.New() e.HideBanner = true e.HidePort = true - e.HTTPErrorHandler = func(err error, c echo.Context) { - if !c.Response().Committed { - http.Error(c.Response(), err.Error(), 500) - } - } + e.HTTPErrorHandler = rsp.HTTPErrorHandler e.Logger = util.NewLogger() e.Use(middleware.Recover()) e.Use(middleware.CORS()) diff --git a/pkg/rsp/error_handler.go b/pkg/rsp/error_handler.go new file mode 100644 index 0000000..ea0754e --- /dev/null +++ b/pkg/rsp/error_handler.go @@ -0,0 +1,14 @@ +package rsp + +import ( + "github.com/labstack/echo/v4" +) + +// HTTPErrorHandler 实现 echo.HTTPErrorHandler 函数 +func HTTPErrorHandler(err error, c echo.Context) { + if c.Response().Committed { + c.Logger().Error(err) + } else if err = Fail(c, err); err != nil { + c.Logger().Error(err) + } +}