From 9f298a9a4ef30b8eb235e53ee510c195e5486be9 Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Fri, 9 Aug 2024 01:54:47 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E8=B0=83=E6=95=B4=20caller=20=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/grpc/interceptor.go | 2 +- pkg/runtime/runtime.go | 27 +++++++++++++++++---------- pkg/runtime/runtime_test.go | 23 ++++++++++++++++++----- 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/pkg/grpc/interceptor.go b/pkg/grpc/interceptor.go index f3a0c0e..486a809 100644 --- a/pkg/grpc/interceptor.go +++ b/pkg/grpc/interceptor.go @@ -20,7 +20,7 @@ func Interceptor(serviceName string, timeout time.Duration) grpc.UnaryServerInte return func(ctx context.Context, req any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { defer func() { if r := recover(); r != nil { - logit.FromContext(ctx).Error("recovery from panic", "r", r, "stack", runtime.Stack()) + logit.FromContext(ctx).Error("recovery from panic", "r", r, "callers", runtime.Callers()) } }() diff --git a/pkg/runtime/runtime.go b/pkg/runtime/runtime.go index 9cb08b7..729582b 100644 --- a/pkg/runtime/runtime.go +++ b/pkg/runtime/runtime.go @@ -6,7 +6,7 @@ package runtime import ( "runtime" - "unsafe" + "strconv" "github.com/FishGoddess/logit" "go.uber.org/automaxprocs/maxprocs" @@ -20,15 +20,22 @@ func init() { } } -const ( - maxStackSize = 4096 // 4KB -) +func Callers() []string { + pcs := make([]uintptr, 16) + n := runtime.Callers(2, pcs) + frames := runtime.CallersFrames(pcs[:n]) + + var callers []string + for { + frame, more := frames.Next() -func Stack() string { - stack := make([]byte, maxStackSize) - n := runtime.Stack(stack, false) - bs := stack[:n] + caller := frame.File + ":" + strconv.Itoa(frame.Line) + callers = append(callers, caller) + + if !more { + break + } + } - bsPtr := unsafe.SliceData(bs) - return unsafe.String(bsPtr, len(bs)) + return callers } diff --git a/pkg/runtime/runtime_test.go b/pkg/runtime/runtime_test.go index 13a67eb..d835315 100644 --- a/pkg/runtime/runtime_test.go +++ b/pkg/runtime/runtime_test.go @@ -4,10 +4,23 @@ package runtime -import "testing" +import ( + "fmt" + "testing" +) -// go test -v -cover -count=1 -test.cpu=1 -run=^TestStack$ -func TestStack(t *testing.T) { - stack := Stack() - t.Log(stack) +// BenchmarkCallers-2 437528 2584 ns/op 748 B/op 12 allocs/op +func BenchmarkCallers(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + Callers() + } +} + +// go test -v -cover -count=1 -test.cpu=1 -run=^TestCallers$ +func TestCallers(t *testing.T) { + callers := Callers() + fmt.Println(callers) } From 838bdd0b6d67c48ba15a05a88f40311c7b699423 Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Sun, 11 Aug 2024 23:07:34 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 2 +- go.sum | 4 +- internal/postar-admin/server/grpc.go | 2 +- internal/postar-admin/service/account.go | 38 ++++++------------ internal/postar-admin/service/space.go | 25 ++++-------- internal/postar-admin/service/template.go | 49 ++++++++--------------- internal/postar-admin/store/account.go | 2 +- internal/postar-admin/store/space.go | 2 +- internal/postar-admin/store/template.go | 2 +- internal/postar/service/email.go | 19 ++++----- internal/postar/store/account.go | 2 +- internal/postar/store/space.go | 2 +- internal/postar/store/template.go | 2 +- pkg/grpc/interceptor.go | 12 +++++- pkg/grpc/status.go | 31 -------------- 15 files changed, 65 insertions(+), 129 deletions(-) delete mode 100644 pkg/grpc/status.go diff --git a/go.mod b/go.mod index f544b23..4e5a25b 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/BurntSushi/toml v1.3.2 github.com/FishGoddess/cachego v0.6.1 github.com/FishGoddess/cryptox v0.4.3 - github.com/FishGoddess/errors v0.5.2 + github.com/FishGoddess/errors v0.6.3-alpha github.com/FishGoddess/logit v1.8.1 github.com/go-sql-driver/mysql v1.7.1 github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0 diff --git a/go.sum b/go.sum index a144b28..2a5afb3 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,8 @@ github.com/FishGoddess/cachego v0.6.1 h1:mbytec3loqw5dcO177LyRGyStKG0AngP5g2GR3S github.com/FishGoddess/cachego v0.6.1/go.mod h1:VLSMwWRlRPazjGYer8pq+4aDrIe1Otj3Yy9HAb0eo3c= github.com/FishGoddess/cryptox v0.4.3 h1:EP1732fzkkgWKi7RSdVje+/pN8WeYFtzdHhJG4JcSs4= github.com/FishGoddess/cryptox v0.4.3/go.mod h1:1j6yGIdxvxJ/V0XThrGhZ+c0NzMi0WxO7WeDFTfNyIM= -github.com/FishGoddess/errors v0.5.2 h1:PYjU6Xb72NXbSKUlwNzHszdUz9/VGS8/CBVAh0U/IwM= -github.com/FishGoddess/errors v0.5.2/go.mod h1:gXd4tNYX6ZFr2XmelF2DHn2uF7oTAi+O9ToJDjNeneE= +github.com/FishGoddess/errors v0.6.3-alpha h1:zYTSXYQcwYlI90JHnnrswMkcjweyobIlZCNeKmNvnpk= +github.com/FishGoddess/errors v0.6.3-alpha/go.mod h1:sjLqiuMcGykL4Wl7/wI13SJF4i+ZfL1ThSlPikZLLh0= github.com/FishGoddess/logit v1.8.1 h1:FQM3A2KHZHT88DmcGibWO2ho69jhwJSYswa6JtsAzGo= github.com/FishGoddess/logit v1.8.1/go.mod h1:6IAtVuIW3AaPTBn2NDfBnML7t0F7/wj1FFeWIPLJy98= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/internal/postar-admin/server/grpc.go b/internal/postar-admin/server/grpc.go index 5a187b9..5b23c57 100644 --- a/internal/postar-admin/server/grpc.go +++ b/internal/postar-admin/server/grpc.go @@ -123,7 +123,7 @@ func checkSpaceInterceptor(spaceService service.SpaceService) grpc.UnaryServerIn if space.Token != spaceToken { err = errors.New("wrong token") - return nil, errors.Forbidden(err, errors.WithMsg("业务空间的令牌错误")) + return nil, errors.Forbidden("业务空间 (%d)%s 的令牌错误", space.ID, space.Name) } return handler(ctx, req) diff --git a/internal/postar-admin/service/account.go b/internal/postar-admin/service/account.go index 554a780..1081054 100644 --- a/internal/postar-admin/service/account.go +++ b/internal/postar-admin/service/account.go @@ -6,7 +6,6 @@ package service import ( "context" - "fmt" "strings" "time" @@ -40,28 +39,23 @@ func NewAccountService(conf *config.PostarAdminConfig, accountStore AccountStore func (das *defaultAccountService) checkCreateAccountParams(account *model.Account) error { if strings.TrimSpace(account.Host) == "" { - err := errors.New("trim account.Host == ''") - return errors.BadRequest(err, errors.WithMsg("账号主机不能为空")) + return errors.BadRequest("账号主机不能为空") } if account.Port <= 0 { - err := errors.New("account.Port <= 0") - return errors.BadRequest(err, errors.WithMsg("账号端口非法")) + return errors.BadRequest("账号端口需要大于 0") } if strings.TrimSpace(account.Username) == "" { - err := errors.New("trim account.Username == ''") - return errors.BadRequest(err, errors.WithMsg("账号用户名不能为空")) + return errors.BadRequest("账号用户名不能为空") } if account.Password == "" { - err := errors.New("account.Password == ''") - return errors.BadRequest(err, errors.WithMsg("账号密码不能为空")) + return errors.BadRequest("账号密码不能为空") } if account.SMTPAuth <= 0 { - err := errors.New("account.SMTPAuth <= 0") - return errors.BadRequest(err, errors.WithMsg("未指定 SMTP 认证方式")) + return errors.BadRequest("未指定 SMTP 认证方式") } return nil @@ -99,13 +93,11 @@ func (das *defaultAccountService) CreateAccount(ctx context.Context, spaceID int func (das *defaultAccountService) checkUpdateAccountParams(account *model.Account) error { if account.ID <= 0 { - err := fmt.Errorf("account.ID %d <= 0", account.ID) - return errors.BadRequest(err, errors.WithMsg("账号编号需要大于 0")) + return errors.BadRequest("账号编号需要大于 0") } if account.State > 0 && !account.State.Valid() { - err := fmt.Errorf("account.State %d not valid", account.State) - return errors.BadRequest(err, errors.WithMsg("账号状态无效")) + return errors.BadRequest("账号状态 %d 无效", account.State) } return nil @@ -142,10 +134,9 @@ func (das *defaultAccountService) UpdateAccount(ctx context.Context, spaceID int return account, nil } -func (das *defaultAccountService) checkGetAccountParams(spaceID int32, accountID int32) error { +func (das *defaultAccountService) checkGetAccountParams(accountID int32) error { if accountID <= 0 { - err := fmt.Errorf("accountID %d <= 0", accountID) - return errors.BadRequest(err, errors.WithMsg("账号编号非法")) + return errors.BadRequest("账号编号需要大于 0") } return nil @@ -154,7 +145,7 @@ func (das *defaultAccountService) checkGetAccountParams(spaceID int32, accountID func (das *defaultAccountService) GetAccount(ctx context.Context, spaceID int32, accountID int32, withPassword bool) (*model.Account, error) { logger := logit.FromContext(ctx) - if err := das.checkGetAccountParams(spaceID, accountID); err != nil { + if err := das.checkGetAccountParams(accountID); err != nil { logger.Error("check get account params failed", "err", err, "account_id", accountID) return nil, err } @@ -182,18 +173,15 @@ func (das *defaultAccountService) GetAccount(ctx context.Context, spaceID int32, func (das *defaultAccountService) checkListAccountsParams(pageSize int32, filter *model.ListAccountsFilter) error { if pageSize < minPageSize || pageSize > maxPageSize { - err := fmt.Errorf("pageSize %d not in [%d, %d]", pageSize, minPageSize, maxPageSize) - return errors.BadRequest(err, errors.WithMsg("分页大小需要位于区间 [%d, %d] 内", minPageSize, maxPageSize)) + return errors.BadRequest("分页大小 %d 需要位于区间 [%d, %d] 内", pageSize, minPageSize, maxPageSize) } if filter.AccountID < 0 { - err := fmt.Errorf("filter.AccountID %d < 0", filter.AccountID) - return errors.BadRequest(err, errors.WithMsg("过滤的账号编号非法")) + return errors.BadRequest("账号编号不能为负数") } if filter.AccountState > 0 && !filter.AccountState.Valid() { - err := fmt.Errorf("filter.AccountState %d not valid", filter.AccountState) - return errors.BadRequest(err, errors.WithMsg("过滤的账号状态非法")) + return errors.BadRequest("账号状态 %d 无效", filter.AccountState) } return nil diff --git a/internal/postar-admin/service/space.go b/internal/postar-admin/service/space.go index 09a2b2b..2bdf33b 100644 --- a/internal/postar-admin/service/space.go +++ b/internal/postar-admin/service/space.go @@ -6,7 +6,6 @@ package service import ( "context" - "fmt" "strings" "time" @@ -41,8 +40,7 @@ func NewSpaceService(conf *config.PostarAdminConfig, spaceStore SpaceStore) Spac func (dss *defaultSpaceService) checkCreateSpaceParams(space *model.Space) error { if strings.TrimSpace(space.Name) == "" { - err := errors.New("trim space.Name == ''") - return errors.BadRequest(err, errors.WithMsg("空间名称不能为空")) + return errors.BadRequest("业务空间名称不能为空") } return nil @@ -80,18 +78,15 @@ func (dss *defaultSpaceService) CreateSpace(ctx context.Context, space *model.Sp func (dss *defaultSpaceService) checkUpdateSpaceParams(space *model.Space) error { if space.ID <= 0 { - err := fmt.Errorf("space.ID %d <= 0", space.ID) - return errors.BadRequest(err, errors.WithMsg("空间编号需要大于 0")) + return errors.BadRequest("业务空间编号需要大于 0") } if strings.TrimSpace(space.Name) == "" { - err := errors.New("trim space.Name == ''") - return errors.BadRequest(err, errors.WithMsg("空间名称不能为空")) + return errors.BadRequest("业务空间名称不能为空") } if space.State > 0 && !space.State.Valid() { - err := fmt.Errorf("space.State %d not valid", space.State) - return errors.BadRequest(err, errors.WithMsg("账号状态无效")) + return errors.BadRequest("业务空间状态 %d 无效", space.State) } return nil @@ -118,8 +113,7 @@ func (dss *defaultSpaceService) UpdateSpace(ctx context.Context, space *model.Sp func (dss *defaultSpaceService) checkGetSpaceParams(spaceID int32) error { if spaceID <= 0 { - err := fmt.Errorf("spaceID %d <= 0", spaceID) - return errors.BadRequest(err, errors.WithMsg("空间编号非法")) + return errors.BadRequest("业务空间编号需要大于 0") } return nil @@ -156,18 +150,15 @@ func (dss *defaultSpaceService) GetSpace(ctx context.Context, spaceID int32, wit func (dss *defaultSpaceService) checkListSpacesParams(pageSize int32, filter *model.ListSpacesFilter) error { if pageSize < minPageSize || pageSize > maxPageSize { - err := fmt.Errorf("pageSize %d not in [%d, %d]", pageSize, minPageSize, maxPageSize) - return errors.BadRequest(err, errors.WithMsg("分页大小需要位于区间 [%d, %d] 内", minPageSize, maxPageSize)) + return errors.BadRequest("分页大小 %d 需要位于区间 [%d, %d] 内", pageSize, minPageSize, maxPageSize) } if filter.SpaceID < 0 { - err := fmt.Errorf("filter.SpaceID %d < 0", filter.SpaceID) - return errors.BadRequest(err, errors.WithMsg("过滤的空间编号非法")) + return errors.BadRequest("业务空间编号不能为负数") } if filter.SpaceState > 0 && !filter.SpaceState.Valid() { - err := fmt.Errorf("filter.SpaceState %d not valid", filter.SpaceState) - return errors.BadRequest(err, errors.WithMsg("过滤的空间状态非法")) + return errors.BadRequest("业务空间状态 %d 无效", filter.SpaceState) } return nil diff --git a/internal/postar-admin/service/template.go b/internal/postar-admin/service/template.go index 0c969ea..f320ba6 100644 --- a/internal/postar-admin/service/template.go +++ b/internal/postar-admin/service/template.go @@ -6,7 +6,6 @@ package service import ( "context" - "fmt" "strings" "time" @@ -40,23 +39,19 @@ func NewTemplateService(conf *config.PostarAdminConfig, templateStore TemplateSt func (dts *defaultTemplateService) checkCreateTemplateParams(template *model.Template) error { if template.AccountID <= 0 { - err := errors.New("template.AccountID <= 0") - return errors.BadRequest(err, errors.WithMsg("模板绑定的账号编号非法")) + return errors.BadRequest("模板绑定的账号编号需要大于 0") } if strings.TrimSpace(template.Name) == "" { - err := errors.New("trim template.Name == ''") - return errors.BadRequest(err, errors.WithMsg("模板名称不能为空")) + return errors.BadRequest("模板名称不能为空") } if strings.TrimSpace(template.Email.Subject) == "" { - err := errors.New("trim template.Email.Subject == ''") - return errors.BadRequest(err, errors.WithMsg("模板邮件主题不能为空")) + return errors.BadRequest("模板邮件主题不能为空") } if !template.Email.ContentType.Valid() { - err := fmt.Errorf("template.Email.ContentType %d not valid", template.Email.ContentType) - return errors.BadRequest(err, errors.WithMsg("模板邮件内容类型无效")) + return errors.BadRequest("模板邮件内容类型 %d 无效", template.Email.ContentType) } return nil @@ -81,33 +76,27 @@ func (dts *defaultTemplateService) CreateTemplate(ctx context.Context, spaceID i func (dts *defaultTemplateService) checkUpdateTemplateParams(template *model.Template) error { if template.ID <= 0 { - err := errors.New("template.ID <= 0") - return errors.BadRequest(err, errors.WithMsg("模板编号非法")) + return errors.BadRequest("模板编号需要大于 0") } if template.AccountID <= 0 { - err := errors.New("template.AccountID <= 0") - return errors.BadRequest(err, errors.WithMsg("模板绑定的账号编号非法")) + return errors.BadRequest("模板绑定的账号编号需要大于 0") } if strings.TrimSpace(template.Name) == "" { - err := errors.New("trim template.Name == ''") - return errors.BadRequest(err, errors.WithMsg("模板名称不能为空")) + return errors.BadRequest("模板名称不能为空") } if strings.TrimSpace(template.Email.Subject) == "" { - err := errors.New("trim template.Email.Subject == ''") - return errors.BadRequest(err, errors.WithMsg("模板邮件主题不能为空")) + return errors.BadRequest("模板邮件主题不能为空") } if template.Email.ContentType > 0 && !template.Email.ContentType.Valid() { - err := fmt.Errorf("template.Email.Content.Type %d not valid", template.Email.ContentType) - return errors.BadRequest(err, errors.WithMsg("模板邮件内容类型无效")) + return errors.BadRequest("模板邮件内容类型 %d 无效", template.Email.ContentType) } if template.State > 0 && !template.State.Valid() { - err := fmt.Errorf("template.State %d not valid", template.State) - return errors.BadRequest(err, errors.WithMsg("模板状态无效")) + return errors.BadRequest("模板状态 %d 无效", template.State) } return nil @@ -130,8 +119,7 @@ func (dts *defaultTemplateService) UpdateTemplate(ctx context.Context, spaceID i func (dts *defaultTemplateService) checkGetTemplateParams(templateID int64) error { if templateID <= 0 { - err := fmt.Errorf("templateID %d <= 0", templateID) - return errors.BadRequest(err, errors.WithMsg("模板编号非法")) + return errors.BadRequest("模板编号需要大于 0") } return nil @@ -150,23 +138,19 @@ func (dts *defaultTemplateService) GetTemplate(ctx context.Context, spaceID int3 func (dts *defaultTemplateService) checkListTemplatesParams(pageSize int32, filter *model.ListTemplatesFilter) error { if pageSize < minPageSize || pageSize > maxPageSize { - err := fmt.Errorf("pageSize %d not in [%d, %d]", pageSize, minPageSize, maxPageSize) - return errors.BadRequest(err, errors.WithMsg("分页大小需要位于区间 [%d, %d] 内", minPageSize, maxPageSize)) + return errors.BadRequest("分页大小 %d 需要位于区间 [%d, %d] 内", pageSize, minPageSize, maxPageSize) } if filter.AccountID < 0 { - err := fmt.Errorf("filter.AccountID %d < 0", filter.AccountID) - return errors.BadRequest(err, errors.WithMsg("过滤的账号编号非法")) + return errors.BadRequest("账号编号不能为负数") } if filter.TemplateID < 0 { - err := fmt.Errorf("filter.TemplateID %d < 0", filter.TemplateID) - return errors.BadRequest(err, errors.WithMsg("过滤的模板编号非法")) + return errors.BadRequest("模板编号不能为负数") } if filter.TemplateState > 0 && !filter.TemplateState.Valid() { - err := fmt.Errorf("filter.TemplateState %d not valid", filter.TemplateState) - return errors.BadRequest(err, errors.WithMsg("过滤的模板状态非法")) + return errors.BadRequest("模板状态 %d 无效", filter.TemplateState) } return nil @@ -198,8 +182,7 @@ func (dts *defaultTemplateService) ListTemplates(ctx context.Context, spaceID in func (dts *defaultTemplateService) checkDeleteTemplateParams(templateID int64) error { if templateID <= 0 { - err := fmt.Errorf("templateID %d <= 0", templateID) - return errors.BadRequest(err, errors.WithMsg("模板编号非法")) + return errors.BadRequest("模板编号需要大于 0") } return nil diff --git a/internal/postar-admin/store/account.go b/internal/postar-admin/store/account.go index d88a42d..37fe28d 100644 --- a/internal/postar-admin/store/account.go +++ b/internal/postar-admin/store/account.go @@ -144,7 +144,7 @@ func (as *AccountStore) newAccount(row *stdsql.Row) (*model.Account, error) { err := row.Scan(&account.ID, &account.Host, &account.Port, &account.Username, &account.Password, &account.SMTPAuth, &account.State, &account.CreateTime, &account.UpdateTime) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("账号不存在")) + return nil, errors.NotFound("账号不存在").With(err) } return account, err diff --git a/internal/postar-admin/store/space.go b/internal/postar-admin/store/space.go index 9210679..9a5653d 100644 --- a/internal/postar-admin/store/space.go +++ b/internal/postar-admin/store/space.go @@ -123,7 +123,7 @@ func (ss *SpaceStore) newSpace(row *stdsql.Row) (*model.Space, error) { err := row.Scan(&space.ID, &space.Name, &space.Token, &space.State, &space.CreateTime, &space.UpdateTime) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("业务空间不存在")) + return nil, errors.NotFound("业务空间不存在").With(err) } return space, err diff --git a/internal/postar-admin/store/template.go b/internal/postar-admin/store/template.go index e7ec124..010359d 100644 --- a/internal/postar-admin/store/template.go +++ b/internal/postar-admin/store/template.go @@ -155,7 +155,7 @@ func (ts *TemplateStore) newTemplate(row *stdsql.Row) (*model.Template, error) { err := row.Scan(&template.ID, &template.AccountID, &template.Name, &template.Description, &template.Email.Subject, &to, &cc, &bcc, &template.Email.ContentType, &template.Email.Content, &template.State, &template.CreateTime, &template.UpdateTime) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("模板不存在")) + return nil, errors.NotFound("模板不存在").With(err) } template.Email.To = decodeStrings(to) diff --git a/internal/postar/service/email.go b/internal/postar/service/email.go index 0598a36..c4f36d7 100644 --- a/internal/postar/service/email.go +++ b/internal/postar/service/email.go @@ -6,7 +6,6 @@ package service import ( "context" - "fmt" "github.com/FishGoddess/errors" "github.com/FishGoddess/logit" @@ -59,8 +58,7 @@ func (des *defaultEmailService) checkSpace(ctx context.Context) (spaceID int32, spaceToken := contextutil.GetSpaceToken(ctx) if spaceID <= 0 { - err = errors.New("wrong space") - return 0, errors.BadRequest(err, errors.WithMsg("业务空间错误")) + return 0, errors.BadRequest("业务空间 %d <= 0", spaceID) } space, err := des.spaceStore.GetSpace(ctx, spaceID) @@ -69,8 +67,7 @@ func (des *defaultEmailService) checkSpace(ctx context.Context) (spaceID int32, } if !space.Enabled() { - err = errors.New("space not enabled") - return 0, errors.BadRequest(err, errors.WithMsg("业务空间未启用")) + return 0, errors.BadRequest("业务空间 (%d)%s 未启用", space.ID, space.Name) } decrypted, err := aes.Decrypt(des.conf.Crypto.AESKey, des.conf.Crypto.AESIV, space.Token) @@ -81,8 +78,7 @@ func (des *defaultEmailService) checkSpace(ctx context.Context) (spaceID int32, space.Token = decrypted if spaceToken != space.Token { - err = errors.New("wrong token") - return 0, errors.Forbidden(err, errors.WithMsg("业务空间的令牌错误")) + return 0, errors.Forbidden("业务空间 (%d)%s 的令牌错误", space.ID, space.Name) } return spaceID, nil @@ -96,7 +92,7 @@ func (des *defaultEmailService) getTemplate(ctx context.Context, spaceID int32, if !template.Enabled() { err = errors.New("template not enabled") - return nil, errors.BadRequest(err, errors.WithMsg("邮件模板未启用")) + return nil, errors.BadRequest("模板 (%d)%s 未启用", template.ID, template.Name) } return template, nil @@ -110,7 +106,7 @@ func (des *defaultEmailService) getAccount(ctx context.Context, spaceID int32, a if !account.Enabled() { err = errors.New("account not enabled") - return nil, errors.BadRequest(err, errors.WithMsg("账号未启用")) + return nil, errors.BadRequest("账号 (%d)%s 未启用", account.ID, account.Username) } decrypted, err := aes.Decrypt(des.conf.Crypto.AESKey, des.conf.Crypto.AESIV, account.Password) @@ -140,8 +136,7 @@ func (des *defaultEmailService) combineTemplateEmail(template *model.Template, e templateEmail.To = append(templateEmail.To, email.To...) if len(templateEmail.To) <= 0 { - err := fmt.Errorf("zero email to") - return nil, errors.BadRequest(err, errors.WithMsg("邮件收件人为空")) + return nil, errors.BadRequest("邮件收件人为空") } templateEmail.CC = append(templateEmail.CC, email.CC...) @@ -218,7 +213,7 @@ func (des *defaultEmailService) sendEmail(ctx context.Context, email *model.Emai } if err = des.handleTemplateEmail(ctx, account, templateEmail); err != nil { - return errors.InternalServerError(err, errors.WithMsg(err.Error())) + return err } return nil diff --git a/internal/postar/store/account.go b/internal/postar/store/account.go index aef6e7a..0ba669d 100644 --- a/internal/postar/store/account.go +++ b/internal/postar/store/account.go @@ -41,7 +41,7 @@ func (as *AccountStore) newAccount(row *stdsql.Row) (*model.Account, error) { err := row.Scan(&account.ID, &account.Host, &account.Port, &account.Username, &account.Password, &account.SMTPAuth, &account.State) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("账号不存在")) + return nil, errors.NotFound("账号不存在").With(err) } return account, err diff --git a/internal/postar/store/space.go b/internal/postar/store/space.go index 843a5b9..ebb33d2 100644 --- a/internal/postar/store/space.go +++ b/internal/postar/store/space.go @@ -40,7 +40,7 @@ func (ss *SpaceStore) newSpace(row *stdsql.Row) (*model.Space, error) { err := row.Scan(&space.ID, &space.Name, &space.Token, &space.State) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("业务空间不存在")) + return nil, errors.NotFound("业务空间不存在").With(err) } return space, err diff --git a/internal/postar/store/template.go b/internal/postar/store/template.go index 47ba320..884893b 100644 --- a/internal/postar/store/template.go +++ b/internal/postar/store/template.go @@ -42,7 +42,7 @@ func (ts *TemplateStore) newTemplate(row *stdsql.Row) (*model.Template, error) { err := row.Scan(&template.ID, &template.AccountID, &template.Name, &template.Email.Subject, &to, &cc, &bcc, &template.Email.ContentType, &template.Email.Content, &template.State) if err == stdsql.ErrNoRows { - return nil, errors.NotFound(err, errors.WithMsg("模板不存在")) + return nil, errors.NotFound("模板不存在").With(err) } template.Email.To = decodeStrings(to) diff --git a/pkg/grpc/interceptor.go b/pkg/grpc/interceptor.go index 486a809..f261e59 100644 --- a/pkg/grpc/interceptor.go +++ b/pkg/grpc/interceptor.go @@ -8,14 +8,24 @@ import ( "context" "time" + "github.com/FishGoddess/errors" "github.com/FishGoddess/logit" "github.com/infra-io/postar/pkg/grpc/contextutil" "github.com/infra-io/postar/pkg/runtime" "github.com/infra-io/postar/pkg/trace" "google.golang.org/grpc" + grpccodes "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + grpcstatus "google.golang.org/grpc/status" ) +func newStatusError(err error) error { + code, msg := errors.CodeMessage(err, 500, "internal server error") + gcode := grpccodes.Code(code) + + return grpcstatus.New(gcode, msg).Err() +} + func Interceptor(serviceName string, timeout time.Duration) grpc.UnaryServerInterceptor { return func(ctx context.Context, req any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { defer func() { @@ -48,7 +58,7 @@ func Interceptor(serviceName string, timeout time.Duration) grpc.UnaryServerInte } else { logger.Error("service method end", "err", err, "request", reqJson, "response", respJson, "cost", cost) - err = wrapStatus(err) + err = newStatusError(err) } }() diff --git a/pkg/grpc/status.go b/pkg/grpc/status.go deleted file mode 100644 index 147a447..0000000 --- a/pkg/grpc/status.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2024 FishGoddess. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package grpc - -import ( - "net/http" - - "github.com/FishGoddess/errors" - "github.com/FishGoddess/errors/status" - grpccodes "google.golang.org/grpc/codes" - grpcstatus "google.golang.org/grpc/status" -) - -func init() { - status.RegisterStatuses( - status.New(http.StatusBadRequest, "Bad Request", errors.IsBadRequest), - status.New(http.StatusForbidden, "Forbidden", errors.IsForbidden), - status.New(http.StatusNotFound, "Not Found", errors.IsNotFound), - status.New(http.StatusRequestTimeout, "Request Timeout", errors.IsRequestTimeout), - status.New(http.StatusInternalServerError, "Internal Server Error", errors.IsInternalServerError), - ) -} - -func wrapStatus(err error) error { - code, msg := status.Parse(err) - gCode := grpccodes.Code(code) - - return grpcstatus.New(gCode, msg).Err() -} From 14e98a2653e9b037f62d7b8cba22e817d44fff3c Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Sun, 11 Aug 2024 23:22:00 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4e5a25b..70b72fd 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/BurntSushi/toml v1.3.2 github.com/FishGoddess/cachego v0.6.1 github.com/FishGoddess/cryptox v0.4.3 - github.com/FishGoddess/errors v0.6.3-alpha + github.com/FishGoddess/errors v0.7.0 github.com/FishGoddess/logit v1.8.1 github.com/go-sql-driver/mysql v1.7.1 github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0 diff --git a/go.sum b/go.sum index 2a5afb3..06080d6 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,8 @@ github.com/FishGoddess/cachego v0.6.1 h1:mbytec3loqw5dcO177LyRGyStKG0AngP5g2GR3S github.com/FishGoddess/cachego v0.6.1/go.mod h1:VLSMwWRlRPazjGYer8pq+4aDrIe1Otj3Yy9HAb0eo3c= github.com/FishGoddess/cryptox v0.4.3 h1:EP1732fzkkgWKi7RSdVje+/pN8WeYFtzdHhJG4JcSs4= github.com/FishGoddess/cryptox v0.4.3/go.mod h1:1j6yGIdxvxJ/V0XThrGhZ+c0NzMi0WxO7WeDFTfNyIM= -github.com/FishGoddess/errors v0.6.3-alpha h1:zYTSXYQcwYlI90JHnnrswMkcjweyobIlZCNeKmNvnpk= -github.com/FishGoddess/errors v0.6.3-alpha/go.mod h1:sjLqiuMcGykL4Wl7/wI13SJF4i+ZfL1ThSlPikZLLh0= +github.com/FishGoddess/errors v0.7.0 h1:yPNSUvvD9xRnhHlZ6SAo/yAjxUGceD/W1ITjhPWu/c4= +github.com/FishGoddess/errors v0.7.0/go.mod h1:sjLqiuMcGykL4Wl7/wI13SJF4i+ZfL1ThSlPikZLLh0= github.com/FishGoddess/logit v1.8.1 h1:FQM3A2KHZHT88DmcGibWO2ho69jhwJSYswa6JtsAzGo= github.com/FishGoddess/logit v1.8.1/go.mod h1:6IAtVuIW3AaPTBn2NDfBnML7t0F7/wj1FFeWIPLJy98= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= From c1510aabd8e8488c85d0834118ead612e34a2065 Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Sun, 11 Aug 2024 23:24:03 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HISTORY.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/HISTORY.md b/HISTORY.md index e05328c..85d6367 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,11 @@ ## ✒ 历史版本的特性介绍 (Features in old versions) +### v0.5.1 + +> 此版本发布于 2024-08-11 + +* 重构错误处理 + ### v0.5.0 > 此版本发布于 2024-08-08 From ae3c49c38d8b69bd67f0c40fc4a18e12e2c105d4 Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Sun, 11 Aug 2024 23:24:25 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 6ed9c0d..55086a1 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: all fmt test build clean proto postar postaradmin -VERSION=v0.5.0 +VERSION=v0.5.1 all: make test && make clean && make build