diff --git a/go.mod b/go.mod index 28024a658..0adc53407 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.18 require ( dubbo.apache.org/dubbo-go/v3 v3.0.3-rc2 github.com/DATA-DOG/go-sqlmock v1.5.0 - github.com/agiledragon/gomonkey v2.0.2+incompatible + github.com/agiledragon/gomonkey/v2 v2.2.0 github.com/apache/dubbo-getty v1.4.9-0.20220825024508-3da63c3257fa github.com/arana-db/parser v0.2.5 github.com/dubbogo/gost v1.12.6-0.20220824084206-300e27e9e524 diff --git a/go.sum b/go.sum index 86187c3e9..03903dc94 100644 --- a/go.sum +++ b/go.sum @@ -70,6 +70,8 @@ github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 h1:rFw4nCn9iMW+Vaj github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw= github.com/agiledragon/gomonkey v2.0.2+incompatible/go.mod h1:2NGfXu1a80LLr2cmWXGBDaHEjb1idR6+FVlX5T3D9hw= +github.com/agiledragon/gomonkey/v2 v2.2.0 h1:QJWqpdEhGV/JJy70sZ/LDnhbSlMrqHAWHcNOjz1kyuI= +github.com/agiledragon/gomonkey/v2 v2.2.0/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= diff --git a/goimports.sh b/goimports.sh old mode 100644 new mode 100755 diff --git a/pkg/datasource/sql/at.go b/pkg/datasource/sql/at.go index e60c3e06b..a78ec672a 100644 --- a/pkg/datasource/sql/at.go +++ b/pkg/datasource/sql/at.go @@ -30,6 +30,7 @@ import ( "github.com/seata/seata-go/pkg/datasource/sql/undo" "github.com/seata/seata-go/pkg/protocol/branch" "github.com/seata/seata-go/pkg/rm" + serr "github.com/seata/seata-go/pkg/util/errors" ) func InitAT(cfg undo.Config, asyncCfg AsyncWorkerConfig) { @@ -87,12 +88,12 @@ func (a *ATSourceManager) BranchRollback(ctx context.Context, branchResource rm. } if err := undoMgr.RunUndo(ctx, branchResource.Xid, branchResource.BranchId, dbResource.db, dbResource.dbName); err != nil { - transErr, ok := err.(*types.TransactionError) + transErr, ok := err.(*serr.SeataError) if !ok { return branch.BranchStatusPhaseoneFailed, err } - if transErr.Code() == types.ErrorCodeBranchRollbackFailedUnretriable { + if transErr.Code == serr.TransactionErrorCodeBranchRollbackFailedUnretriable { return branch.BranchStatusPhasetwoRollbackFailedUnretryable, nil } diff --git a/pkg/datasource/sql/datasource/base/meta_cache.go b/pkg/datasource/sql/datasource/base/meta_cache.go index e2088a64d..1edbf38e4 100644 --- a/pkg/datasource/sql/datasource/base/meta_cache.go +++ b/pkg/datasource/sql/datasource/base/meta_cache.go @@ -20,7 +20,7 @@ package base import ( "context" "database/sql" - "errors" + "fmt" "sync" "time" @@ -154,7 +154,7 @@ func (c *BaseTableMetaCache) GetTableMeta(ctx context.Context, dbName, tableName return *meta, nil } - return types.TableMeta{}, errors.New("not found table metadata") + return types.TableMeta{}, fmt.Errorf("not found table metadata") } v.lastAccess = time.Now() diff --git a/pkg/datasource/sql/datasource/datasource_manager.go b/pkg/datasource/sql/datasource/datasource_manager.go index 0d1f4fdcf..94f12352b 100644 --- a/pkg/datasource/sql/datasource/datasource_manager.go +++ b/pkg/datasource/sql/datasource/datasource_manager.go @@ -20,7 +20,7 @@ package datasource import ( "context" "database/sql" - "errors" + "fmt" "sync" "github.com/seata/seata-go/pkg/datasource/sql/types" @@ -120,7 +120,7 @@ func (dm *BasicSourceManager) RegisterResource(resource rm.Resource) error { // Unregister a model.Resource from the model.Resource Manager func (dm *BasicSourceManager) UnregisterResource(resource rm.Resource) error { - return errors.New("unsupport unregister resource") + return fmt.Errorf("unsupport unregister resource") } // Get all resources managed by this manager diff --git a/pkg/datasource/sql/datasource/mysql/meta_cache.go b/pkg/datasource/sql/datasource/mysql/meta_cache.go index 14ca88a5d..94e730e84 100644 --- a/pkg/datasource/sql/datasource/mysql/meta_cache.go +++ b/pkg/datasource/sql/datasource/mysql/meta_cache.go @@ -20,11 +20,10 @@ package mysql import ( "context" "database/sql" + "fmt" "sync" "time" - "github.com/pkg/errors" - "github.com/seata/seata-go/pkg/datasource/sql/datasource/base" "github.com/seata/seata-go/pkg/datasource/sql/types" ) @@ -56,7 +55,7 @@ func (c *TableMetaCache) Init(ctx context.Context, conn *sql.DB) error { // GetTableMeta get table info from cache or information schema func (c *TableMetaCache) GetTableMeta(ctx context.Context, dbName, tableName string) (*types.TableMeta, error) { if tableName == "" { - return nil, errors.New("table name is empty") + return nil, fmt.Errorf("table name is empty") } conn, err := c.db.Conn(ctx) diff --git a/pkg/datasource/sql/datasource/mysql/trigger.go b/pkg/datasource/sql/datasource/mysql/trigger.go index 34622ecbf..af26097e3 100644 --- a/pkg/datasource/sql/datasource/mysql/trigger.go +++ b/pkg/datasource/sql/datasource/mysql/trigger.go @@ -20,6 +20,7 @@ package mysql import ( "context" "database/sql" + "fmt" "strings" "github.com/pkg/errors" @@ -70,7 +71,7 @@ func (m *mysqlTrigger) LoadOne(ctx context.Context, dbName string, tableName str } } if len(tableMeta.Indexs) == 0 { - return nil, errors.Errorf("Could not found any index in the table: %s", tableName) + return nil, fmt.Errorf("could not found any index in the table: %s", tableName) } return &tableMeta, nil @@ -144,7 +145,7 @@ func (m *mysqlTrigger) getColumnMetas(ctx context.Context, dbName string, table } if len(columnMetas) == 0 { - return nil, errors.New("can't find column") + return nil, fmt.Errorf("can't find column") } return columnMetas, nil diff --git a/pkg/datasource/sql/exec/at/insert_executor_test.go b/pkg/datasource/sql/exec/at/insert_executor_test.go index f505c9690..804327cdb 100644 --- a/pkg/datasource/sql/exec/at/insert_executor_test.go +++ b/pkg/datasource/sql/exec/at/insert_executor_test.go @@ -23,7 +23,7 @@ import ( "reflect" "testing" - "github.com/agiledragon/gomonkey" + "github.com/agiledragon/gomonkey/v2" "github.com/arana-db/parser/ast" "github.com/arana-db/parser/model" "github.com/arana-db/parser/test_driver" diff --git a/pkg/datasource/sql/exec/at/update_executor_test.go b/pkg/datasource/sql/exec/at/update_executor_test.go index dc32288ea..9e01720ae 100644 --- a/pkg/datasource/sql/exec/at/update_executor_test.go +++ b/pkg/datasource/sql/exec/at/update_executor_test.go @@ -23,8 +23,7 @@ import ( "reflect" "testing" - "github.com/agiledragon/gomonkey" - _ "github.com/arana-db/parser/test_driver" + "github.com/agiledragon/gomonkey/v2" "github.com/seata/seata-go/pkg/datasource/sql/datasource" "github.com/seata/seata-go/pkg/datasource/sql/datasource/mysql" "github.com/seata/seata-go/pkg/datasource/sql/exec" diff --git a/pkg/datasource/sql/tx.go b/pkg/datasource/sql/tx.go index 296c0b561..78db4fbb8 100644 --- a/pkg/datasource/sql/tx.go +++ b/pkg/datasource/sql/tx.go @@ -20,10 +20,9 @@ package sql import ( "context" "database/sql/driver" + "fmt" "sync" - "github.com/pkg/errors" - "github.com/seata/seata-go/pkg/datasource/sql/datasource" "github.com/seata/seata-go/pkg/protocol/branch" "github.com/seata/seata-go/pkg/rm" @@ -183,7 +182,7 @@ func (tx *Tx) report(success bool) error { } dataSourceManager := datasource.GetDataSourceManager(tx.tranCtx.TransactionMode.BranchType()) if dataSourceManager == nil { - return errors.New("get dataSourceManager failed") + return fmt.Errorf("get dataSourceManager failed") } retry := REPORT_RETRY_COUNT for retry > 0 { diff --git a/pkg/datasource/sql/types/error.go b/pkg/datasource/sql/types/error.go deleted file mode 100644 index ae05bbf1b..000000000 --- a/pkg/datasource/sql/types/error.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package types - -type ErrorCode int32 - -const ( - _ ErrorCode = iota - ErrorCodeUnknown - ErrorCodeBeginFailed - ErrorCodeLockKeyConflict - ErrorCodeIO - ErrorCodeBranchRollbackFailedRetriable - ErrorCodeBranchRollbackFailedUnretriable - ErrorCodeBranchRegisterFailed - ErrorCodeBranchReportFailed - ErrorCodeLockableCheckFailed - ErrorCodeBranchTransactionNotExist - ErrorCodeGlobalTransactionNotExist - ErrorCodeGlobalTransactionNotActive - ErrorCodeGlobalTransactionStatusInvalid - ErrorCodeFailedToSendBranchCommitRequest - ErrorCodeFailedToSendBranchRollbackRequest - ErrorCodeFailedToAddBranch - ErrorCodeFailedWriteSession - ErrorCodeFailedLockGlobalTranscation - ErrorCodeFailedStore - ErrorCodeLockKeyConflictFailFast -) - -type TransactionError struct { - code ErrorCode - msg string -} - -func (e *TransactionError) Error() string { - return e.msg -} - -func (e *TransactionError) Code() ErrorCode { - return e.code -} diff --git a/pkg/datasource/sql/types/meta.go b/pkg/datasource/sql/types/meta.go index 90722cae2..a67a1f5a4 100644 --- a/pkg/datasource/sql/types/meta.go +++ b/pkg/datasource/sql/types/meta.go @@ -18,9 +18,8 @@ package types import ( + "fmt" "reflect" - - "github.com/pkg/errors" ) // ColumnMeta @@ -132,7 +131,7 @@ func (m TableMeta) GetPrimaryKeyType() (int32, error) { } } } - return 0, errors.New("get primary key type error") + return 0, fmt.Errorf("get primary key type error") } // GetPrimaryKeyTypeStrMap get all PK type to map @@ -146,7 +145,7 @@ func (m TableMeta) GetPrimaryKeyTypeStrMap() (map[string]string, error) { } } if len(pkMap) == 0 { - return nil, errors.New("get primary key type error") + return nil, fmt.Errorf("get primary key type error") } return pkMap, nil } diff --git a/pkg/datasource/sql/undo/base/undo.go b/pkg/datasource/sql/undo/base/undo.go index de9405170..3f16099c3 100644 --- a/pkg/datasource/sql/undo/base/undo.go +++ b/pkg/datasource/sql/undo/base/undo.go @@ -27,7 +27,6 @@ import ( "strings" "github.com/arana-db/parser/mysql" - "github.com/pkg/errors" "github.com/seata/seata-go/pkg/datasource/sql/datasource" "github.com/seata/seata-go/pkg/datasource/sql/types" "github.com/seata/seata-go/pkg/datasource/sql/undo" @@ -433,7 +432,7 @@ func (m *BaseUndoLogManager) appendInParam(size int, str *strings.Builder) { func Int64Slice2Str(values interface{}, sep string) (string, error) { v, ok := values.([]int64) if !ok { - return "", errors.New("param type is fault") + return "", fmt.Errorf("param type is fault") } var valuesText []string diff --git a/pkg/datasource/sql/undo/builder/mysql_insert_undo_log_builder.go b/pkg/datasource/sql/undo/builder/mysql_insert_undo_log_builder.go index de2d998d6..768417095 100644 --- a/pkg/datasource/sql/undo/builder/mysql_insert_undo_log_builder.go +++ b/pkg/datasource/sql/undo/builder/mysql_insert_undo_log_builder.go @@ -20,10 +20,10 @@ package builder import ( "context" "database/sql/driver" + "fmt" "strings" "github.com/arana-db/parser/ast" - "github.com/pkg/errors" "github.com/seata/seata-go/pkg/datasource/sql/types" "github.com/seata/seata-go/pkg/datasource/sql/undo" "github.com/seata/seata-go/pkg/datasource/sql/undo/executor" @@ -91,12 +91,12 @@ func (u *MySQLInsertUndoLogBuilder) AfterImage(ctx context.Context, execCtx *typ func (u *MySQLInsertUndoLogBuilder) buildAfterImageSQL(ctx context.Context, execCtx *types.ExecContext) (string, []driver.Value, error) { // get all pk value if execCtx == nil || execCtx.ParseContext == nil || execCtx.ParseContext.InsertStmt == nil { - return "", nil, errors.New("can't found execCtx or ParseContext or InsertStmt") + return "", nil, fmt.Errorf("can't found execCtx or ParseContext or InsertStmt") } parseCtx := execCtx.ParseContext tableName := execCtx.ParseContext.InsertStmt.Table.TableRefs.Left.(*ast.TableSource).Source.(*ast.TableName).Name.O if execCtx.MetaDataMap == nil { - return "", nil, errors.New("can't found MetaDataMap") + return "", nil, fmt.Errorf("can't found MetaDataMap") } meta := execCtx.MetaDataMap[tableName] pkValuesMap, err := u.getPkValues(execCtx, parseCtx, meta) @@ -106,7 +106,7 @@ func (u *MySQLInsertUndoLogBuilder) buildAfterImageSQL(ctx context.Context, exec pkColumnNameList := meta.GetPrimaryKeyOnlyName() if len(pkColumnNameList) == 0 { - return "", nil, errors.New("Pk columnName size is zero") + return "", nil, fmt.Errorf("Pk columnName size is zero") } dataTypeMap, err := meta.GetPrimaryKeyTypeStrMap() @@ -114,7 +114,7 @@ func (u *MySQLInsertUndoLogBuilder) buildAfterImageSQL(ctx context.Context, exec return "", nil, err } if len(dataTypeMap) != len(pkColumnNameList) { - return "", nil, errors.New("PK columnName size don't equal PK DataType size") + return "", nil, fmt.Errorf("PK columnName size don't equal PK DataType size") } var pkRowImages []types.RowImage @@ -272,7 +272,7 @@ func (u *MySQLInsertUndoLogBuilder) parsePkValuesFromStatement(insertStmt *ast.I } pkIndexMap := u.getPkIndex(insertStmt, meta) if pkIndexMap == nil || len(pkIndexMap) == 0 { - return nil, errors.New("pkIndex is not found") + return nil, fmt.Errorf("pkIndex is not found") } var pkIndexArray []int for _, val := range pkIndexMap { @@ -281,7 +281,7 @@ func (u *MySQLInsertUndoLogBuilder) parsePkValuesFromStatement(insertStmt *ast.I } if insertStmt == nil || len(insertStmt.Lists) == 0 { - return nil, errors.New("parCtx is nil, perhaps InsertStmt is empty") + return nil, fmt.Errorf("parCtx is nil, perhaps InsertStmt is empty") } pkValuesMap := make(map[string][]interface{}) @@ -349,7 +349,7 @@ func (u *MySQLInsertUndoLogBuilder) parsePkValuesFromStatement(insertStmt *ast.I tmpPkName := pkName tmpPkIndex := pkIndex if tmpPkIndex >= len(list) { - return nil, errors.New("pkIndex out of range") + return nil, fmt.Errorf("pkIndex out of range") } if node, ok := list[tmpPkIndex].(ast.ValueExpr); ok { pkValuesMap[tmpPkName] = append(pkValuesMap[tmpPkName], node.GetValue()) @@ -407,7 +407,7 @@ func (u *MySQLInsertUndoLogBuilder) getPkValuesByAuto(execCtx *types.ExecContext pkValuesMap := make(map[string][]interface{}) pkMetaMap := metaData.GetPrimaryKeyMap() if len(pkMetaMap) == 0 { - return nil, errors.New("pk map is empty") + return nil, fmt.Errorf("pk map is empty") } var autoColumnName string for _, columnMeta := range pkMetaMap { @@ -418,7 +418,7 @@ func (u *MySQLInsertUndoLogBuilder) getPkValuesByAuto(execCtx *types.ExecContext } } if len(autoColumnName) == 0 { - return nil, errors.New("auto increment column not exist") + return nil, fmt.Errorf("auto increment column not exist") } updateCount, err := u.InsertResult.GetResult().RowsAffected() @@ -485,12 +485,12 @@ func (u *MySQLInsertUndoLogBuilder) autoGeneratePks(execCtx *types.ExecContext, step = curStepInt } } else { - return nil, errors.New("query is empty") + return nil, fmt.Errorf("query is empty") } } if step == 0 { - return nil, errors.New("get increment step error") + return nil, fmt.Errorf("get increment step error") } var pkValues []interface{} @@ -542,7 +542,7 @@ func getInsertRows(insertStmt *ast.InsertStmt, pkIndexArray []int) ([][]interfac } else { for _, index := range pkIndexArray { if index == i { - return nil, errors.Errorf("Unknown SQLExpr:%v", node) + return nil, fmt.Errorf("Unknown SQLExpr:%v", node) } } row = append(row, ast.DefaultExpr{}) diff --git a/pkg/datasource/sql/undo/builder/mysql_multi_update_undo_log_builder.go b/pkg/datasource/sql/undo/builder/mysql_multi_update_undo_log_builder.go index 7583fa4da..8a0cfd857 100644 --- a/pkg/datasource/sql/undo/builder/mysql_multi_update_undo_log_builder.go +++ b/pkg/datasource/sql/undo/builder/mysql_multi_update_undo_log_builder.go @@ -158,10 +158,10 @@ func (u *MySQLMultiUpdateUndoLogBuilder) buildBeforeImageSQL(updateStmts []*ast. var whereCondition strings.Builder for _, updateStmt := range updateStmts { if updateStmt.Limit != nil { - return "", nil, errors.New("multi update SQL with limit condition is not support yet") + return "", nil, fmt.Errorf("multi update SQL with limit condition is not support yet") } if updateStmt.Order != nil { - return "", nil, errors.New("multi update SQL with orderBy condition is not support yet") + return "", nil, fmt.Errorf("multi update SQL with orderBy condition is not support yet") } // todo use ONLY_CARE_UPDATE_COLUMNS to judge select all columns or not @@ -213,7 +213,7 @@ func (u *MySQLMultiUpdateUndoLogBuilder) buildBeforeImageSQL(updateStmts []*ast. } fakeSelectStmt, ok := fakeNode.(*ast.SelectStmt) if !ok { - return "", nil, errors.New("multi update fake node is not select stmt") + return "", nil, fmt.Errorf("multi update fake node is not select stmt") } selStmt := ast.SelectStmt{ diff --git a/pkg/datasource/sql/undo/builder/mysql_update_undo_log_builder_test.go b/pkg/datasource/sql/undo/builder/mysql_update_undo_log_builder_test.go index 6a7a36d93..c6ee25eb2 100644 --- a/pkg/datasource/sql/undo/builder/mysql_update_undo_log_builder_test.go +++ b/pkg/datasource/sql/undo/builder/mysql_update_undo_log_builder_test.go @@ -23,9 +23,10 @@ import ( "reflect" "testing" + "github.com/agiledragon/gomonkey/v2" + "github.com/seata/seata-go/pkg/datasource/sql/datasource" - "github.com/agiledragon/gomonkey" "github.com/seata/seata-go/pkg/datasource/sql/datasource/mysql" "github.com/seata/seata-go/pkg/datasource/sql/types" diff --git a/pkg/datasource/sql/undo/executor/mysql_undo_delete_executor.go b/pkg/datasource/sql/undo/executor/mysql_undo_delete_executor.go index 13552d06a..da5536c00 100644 --- a/pkg/datasource/sql/undo/executor/mysql_undo_delete_executor.go +++ b/pkg/datasource/sql/undo/executor/mysql_undo_delete_executor.go @@ -23,8 +23,6 @@ import ( "fmt" "strings" - "github.com/pkg/errors" - "github.com/seata/seata-go/pkg/datasource/sql/types" "github.com/seata/seata-go/pkg/datasource/sql/undo" ) @@ -82,7 +80,7 @@ func (m *mySQLUndoDeleteExecutor) buildUndoSQL(dbType types.DBType) (string, err beforeImage := m.sqlUndoLog.BeforeImage rows := beforeImage.Rows if len(rows) == 0 { - return "", errors.New("invalid undo log") + return "", fmt.Errorf("invalid undo log") } row := rows[0] diff --git a/pkg/datasource/sql/undo/executor/mysql_undo_insert_executor.go b/pkg/datasource/sql/undo/executor/mysql_undo_insert_executor.go index a7fe0967b..53c905812 100644 --- a/pkg/datasource/sql/undo/executor/mysql_undo_insert_executor.go +++ b/pkg/datasource/sql/undo/executor/mysql_undo_insert_executor.go @@ -20,7 +20,6 @@ package executor import ( "context" "database/sql" - "errors" "fmt" "github.com/seata/seata-go/pkg/datasource/sql/types" @@ -75,7 +74,7 @@ func (m *mySQLUndoInsertExecutor) buildUndoSQL(dbType types.DBType) (string, err afterImage := m.sqlUndoLog.AfterImage rows := afterImage.Rows if len(rows) == 0 { - return "", errors.New("invalid undo log") + return "", fmt.Errorf("invalid undo log") } str, err := m.generateDeleteSql(afterImage, rows, dbType, m.sqlUndoLog) diff --git a/pkg/datasource/sql/undo/undo.go b/pkg/datasource/sql/undo/undo.go index 8593291a3..847331214 100644 --- a/pkg/datasource/sql/undo/undo.go +++ b/pkg/datasource/sql/undo/undo.go @@ -21,7 +21,7 @@ import ( "context" "database/sql" "database/sql/driver" - "errors" + "fmt" "sync" "github.com/seata/seata-go/pkg/datasource/sql/types" @@ -84,7 +84,7 @@ func GetUndoLogManager(d types.DBType) (UndoLogManager, error) { v, ok := undoLogManagerMap[d] if !ok { - return nil, errors.New("not found UndoLogManager") + return nil, fmt.Errorf("not found UndoLogManager") } v.once.Do(func() { diff --git a/pkg/remoting/getty/getty_client.go b/pkg/remoting/getty/getty_client.go index 5489a46ae..b00042499 100644 --- a/pkg/remoting/getty/getty_client.go +++ b/pkg/remoting/getty/getty_client.go @@ -18,10 +18,10 @@ package getty import ( + "fmt" "sync" gxtime "github.com/dubbogo/gost/time" - "github.com/pkg/errors" "github.com/seata/seata-go/pkg/protocol/codec" "github.com/seata/seata-go/pkg/protocol/message" "github.com/seata/seata-go/pkg/util/log" @@ -97,7 +97,7 @@ func (g *GettyRemotingClient) syncCallback(reqMsg message.RpcMessage, respMsg *m case <-gxtime.GetDefaultTimerWheel().After(RpcRequestTimeout): GetGettyRemotingInstance().RemoveMergedMessageFuture(reqMsg.ID) log.Errorf("wait resp timeout: %#v", reqMsg) - return nil, errors.Errorf("wait response timeout, request: %#v", reqMsg) + return nil, fmt.Errorf("wait response timeout, request: %#v", reqMsg) case <-respMsg.Done: return respMsg.Response, respMsg.Err } diff --git a/pkg/remoting/getty/getty_client_test.go b/pkg/remoting/getty/getty_client_test.go index 5e6ff7e90..41b96e5e1 100644 --- a/pkg/remoting/getty/getty_client_test.go +++ b/pkg/remoting/getty/getty_client_test.go @@ -22,11 +22,12 @@ import ( "reflect" "testing" + "github.com/agiledragon/gomonkey/v2" + "github.com/seata/seata-go/pkg/protocol/codec" "github.com/seata/seata-go/pkg/protocol/message" "github.com/seata/seata-go/pkg/util/log" - "github.com/agiledragon/gomonkey" getty "github.com/apache/dubbo-getty" "github.com/stretchr/testify/assert" ) diff --git a/pkg/remoting/getty/rpc_client.go b/pkg/remoting/getty/rpc_client.go index fca771367..1aaca738a 100644 --- a/pkg/remoting/getty/rpc_client.go +++ b/pkg/remoting/getty/rpc_client.go @@ -28,8 +28,8 @@ import ( "github.com/seata/seata-go/pkg/util/log" getty "github.com/apache/dubbo-getty" + gxsync "github.com/dubbogo/gost/sync" - "github.com/pkg/errors" ) type RpcClient struct { @@ -106,7 +106,7 @@ func (c *RpcClient) newSession(session getty.Session) error { if _, ok = session.Conn().(*tls.Conn); !ok { if tcpConn, ok = session.Conn().(*net.TCPConn); !ok { - return errors.New(fmt.Sprintf("%s, session.conn{%#v} is not tcp connection", session.Stat(), session.Conn())) + return fmt.Errorf("%s, session.conn{%#v} is not tcp connection", session.Stat(), session.Conn()) } if err = tcpConn.SetNoDelay(c.gettyConf.SessionConfig.TCPNoDelay); err != nil { diff --git a/pkg/rm/rm_remoting.go b/pkg/rm/rm_remoting.go index 879298469..ee390ff5a 100644 --- a/pkg/rm/rm_remoting.go +++ b/pkg/rm/rm_remoting.go @@ -130,7 +130,7 @@ func isRegisterSuccess(response interface{}) bool { func isReportSuccess(response interface{}) error { if res, ok := response.(message.BranchReportResponse); ok { if res.ResultCode == message.ResultCodeFailed { - return errors.New(res.Msg) + return fmt.Errorf(res.Msg) } } else { return ErrBranchReportResponseFault diff --git a/pkg/rm/tcc/fence/fence_api.go b/pkg/rm/tcc/fence/fence_api.go index a1b98d166..dbed3af5c 100644 --- a/pkg/rm/tcc/fence/fence_api.go +++ b/pkg/rm/tcc/fence/fence_api.go @@ -25,7 +25,6 @@ import ( "github.com/seata/seata-go/pkg/rm/tcc/fence/enum" "github.com/seata/seata-go/pkg/rm/tcc/fence/handler" "github.com/seata/seata-go/pkg/tm" - "github.com/seata/seata-go/pkg/util/errors" "github.com/seata/seata-go/pkg/util/log" ) @@ -42,11 +41,7 @@ func WithFence(ctx context.Context, tx *sql.Tx, callback func() error) (err erro switch { case fp == enum.FencePhaseNotExist: - err = errors.NewTccFenceError( - errors.FencePhaseError, - fmt.Sprintf("xid %s, tx name %s, fence phase not exist", tm.GetXID(ctx), tm.GetTxName(ctx)), - nil, - ) + err = fmt.Errorf("xid %s, tx name %s, fence phase not exist", tm.GetXID(ctx), tm.GetTxName(ctx)) case fp == enum.FencePhasePrepare: err = h.PrepareFence(ctx, tx, callback) case fp == enum.FencePhaseCommit: @@ -54,11 +49,7 @@ func WithFence(ctx context.Context, tx *sql.Tx, callback func() error) (err erro case fp == enum.FencePhaseRollback: err = h.RollbackFence(ctx, tx, callback) default: - err = errors.NewTccFenceError( - errors.FencePhaseError, - fmt.Sprintf("fence phase: %v illegal", fp), - nil, - ) + err = fmt.Errorf("fence phase: %v illegal", fp) } if err != nil { diff --git a/pkg/rm/tcc/fence/fence_api_test.go b/pkg/rm/tcc/fence/fence_api_test.go index 7e8e0494c..5567f5d78 100644 --- a/pkg/rm/tcc/fence/fence_api_test.go +++ b/pkg/rm/tcc/fence/fence_api_test.go @@ -20,12 +20,10 @@ package fence import ( "context" "database/sql" - "fmt" "testing" "github.com/seata/seata-go/pkg/rm/tcc/fence/enum" "github.com/seata/seata-go/pkg/tm" - "github.com/seata/seata-go/pkg/util/errors" "github.com/seata/seata-go/pkg/util/log" "github.com/DATA-DOG/go-sqlmock" @@ -52,14 +50,9 @@ func TestWithFence(t *testing.T) { return nil }, wantErr: true, - errStr: errors.NewTccFenceError( - errors.FencePhaseError, - fmt.Sprintf("xid 123, tx name test, fence phase not exist"), - nil, - ).Error(), + errStr: "xid 123, tx name test, fence phase not exist", }, } - for _, v := range tests { db, mock, _ := sqlmock.New() mock.ExpectBegin() diff --git a/pkg/rm/tcc/fence/handler/tcc_fence_wrapper_handler.go b/pkg/rm/tcc/fence/handler/tcc_fence_wrapper_handler.go index 1776401c8..78abd104f 100644 --- a/pkg/rm/tcc/fence/handler/tcc_fence_wrapper_handler.go +++ b/pkg/rm/tcc/fence/handler/tcc_fence_wrapper_handler.go @@ -21,7 +21,9 @@ import ( "container/list" "context" "database/sql" + "errors" "fmt" + "github.com/go-sql-driver/mysql" "sync" "time" @@ -29,7 +31,6 @@ import ( "github.com/seata/seata-go/pkg/rm/tcc/fence/store/db/dao" "github.com/seata/seata-go/pkg/rm/tcc/fence/store/db/model" "github.com/seata/seata-go/pkg/tm" - seataErrors "github.com/seata/seata-go/pkg/util/errors" "github.com/seata/seata-go/pkg/util/log" ) @@ -73,27 +74,17 @@ func (handler *tccFenceWrapperHandler) PrepareFence(ctx context.Context, tx *sql err := handler.insertTCCFenceLog(tx, xid, branchId, actionName, enum.StatusTried) if err != nil { - dbError, ok := err.(seataErrors.TccFenceError) - if ok && dbError.Code == seataErrors.TccFenceDbDuplicateKeyError { + if mysqlError, ok := errors.Unwrap(err).(*mysql.MySQLError); ok && mysqlError.Number == 1062 { // todo add clean command to channel. handler.pushCleanChannel(xid, branchId) } - - return seataErrors.NewTccFenceError( - seataErrors.PrepareFenceError, - fmt.Sprintf("insert tcc fence record errors, prepare fence failed. xid= %s, branchId= %d", xid, branchId), - err, - ) + return fmt.Errorf("insert tcc fence record errors, prepare fence failed. xid= %s, branchId= %d, [%w]", xid, branchId, err) } log.Info("the phase 1 callback method will be called.") err = callback() if err != nil { - return seataErrors.NewTccFenceError( - seataErrors.FenceBusinessError, - fmt.Sprintf("the business method error msg of: %p", callback), - err, - ) + return fmt.Errorf("the business method error msg of: %p, [%w]", callback, err) } return nil @@ -105,16 +96,10 @@ func (handler *tccFenceWrapperHandler) CommitFence(ctx context.Context, tx *sql. fenceDo, err := handler.tccFenceDao.QueryTCCFenceDO(tx, xid, branchId) if err != nil { - return seataErrors.NewTccFenceError(seataErrors.CommitFenceError, - fmt.Sprintf(" commit fence method failed. xid= %s, branchId= %d ", xid, branchId), - err, - ) + return fmt.Errorf(" commit fence method failed. xid= %s, branchId= %d, [%w]", xid, branchId, err) } if fenceDo == nil { - return seataErrors.NewTccFenceError(seataErrors.CommitFenceError, - fmt.Sprintf("tcc fence record not exists, commit fence method failed. xid= %s, branchId= %d ", xid, branchId), - err, - ) + return fmt.Errorf("tcc fence record not exists, commit fence method failed. xid= %s, branchId= %d", xid, branchId) } if fenceDo.Status == enum.StatusCommitted { @@ -124,10 +109,7 @@ func (handler *tccFenceWrapperHandler) CommitFence(ctx context.Context, tx *sql. if fenceDo.Status == enum.StatusRollbacked || fenceDo.Status == enum.StatusSuspended { // enable warn level log.Warnf("branch transaction status is unexpected. xid: %s, branchId: %d, status: %s", xid, branchId, fenceDo.Status) - return seataErrors.NewTccFenceError(seataErrors.CommitFenceError, - fmt.Sprintf("branch transaction status is unexpected. xid: %s, branchId: %d, status: %d", xid, branchId, fenceDo.Status), - nil, - ) + return fmt.Errorf("branch transaction status is unexpected. xid: %s, branchId: %d, status: %d", xid, branchId, fenceDo.Status) } return handler.updateFenceStatusAndInvokeCallback(tx, callback, xid, branchId, enum.StatusCommitted) @@ -139,20 +121,14 @@ func (handler *tccFenceWrapperHandler) RollbackFence(ctx context.Context, tx *sq actionName := tm.GetBusinessActionContext(ctx).ActionName fenceDo, err := handler.tccFenceDao.QueryTCCFenceDO(tx, xid, branchId) if err != nil { - return seataErrors.NewTccFenceError(seataErrors.RollbackFenceError, - fmt.Sprintf(" rollback fence method failed. xid= %s, branchId= %d ", xid, branchId), - err, - ) + return fmt.Errorf("rollback fence method failed. xid= %s, branchId= %d, [%w]", xid, branchId, err) } // record is null, mean the need suspend if fenceDo == nil { err = handler.insertTCCFenceLog(tx, xid, branchId, actionName, enum.StatusSuspended) if err != nil { - return seataErrors.NewTccFenceError(seataErrors.RollbackFenceError, - fmt.Sprintf("insert tcc fence suspend record error, rollback fence method failed. xid= %s, branchId= %d", xid, branchId), - err, - ) + return fmt.Errorf("insert tcc fence record errors, rollback fence failed. xid= %s, branchId= %d, [%w]", xid, branchId, err) } log.Infof("Insert tcc fence suspend record xid: %s, branchId: %d", xid, branchId) return nil @@ -166,10 +142,7 @@ func (handler *tccFenceWrapperHandler) RollbackFence(ctx context.Context, tx *sq } if fenceDo.Status == enum.StatusCommitted { log.Warnf("Branch transaction status is unexpected. xid: %s, branchId: %d, status: %d", xid, branchId, fenceDo.Status) - return seataErrors.NewTccFenceError(seataErrors.RollbackFenceError, - fmt.Sprintf("branch transaction status is unexpected. xid: %s, branchId: %d, status: %d", xid, branchId, fenceDo.Status), - err, - ) + return fmt.Errorf("branch transaction status is unexpected. xid: %s, branchId: %d, status: %d", xid, branchId, fenceDo.Status) } return handler.updateFenceStatusAndInvokeCallback(tx, callback, xid, branchId, enum.StatusRollbacked) @@ -192,11 +165,7 @@ func (handler *tccFenceWrapperHandler) updateFenceStatusAndInvokeCallback(tx *sq log.Infof("the phase %d callback method will be called", status) if err := callback(); err != nil { - return seataErrors.NewTccFenceError( - seataErrors.FenceBusinessError, - fmt.Sprintf("the business method error msg of: %p", callback), - err, - ) + return fmt.Errorf("the business method error msg of: %p, [%w]", callback, err) } return nil diff --git a/pkg/rm/tcc/fence/store/db/dao/tcc_fence_db.go b/pkg/rm/tcc/fence/store/db/dao/tcc_fence_db.go index 80290b213..c26277077 100644 --- a/pkg/rm/tcc/fence/store/db/dao/tcc_fence_db.go +++ b/pkg/rm/tcc/fence/store/db/dao/tcc_fence_db.go @@ -29,7 +29,6 @@ import ( "github.com/seata/seata-go/pkg/rm/tcc/fence/enum" "github.com/seata/seata-go/pkg/rm/tcc/fence/store/db/model" sql2 "github.com/seata/seata-go/pkg/rm/tcc/fence/store/db/sql" - "github.com/seata/seata-go/pkg/util/errors" ) var ( @@ -61,7 +60,7 @@ type TccFenceStoreDatabaseMapper struct { func (t *TccFenceStoreDatabaseMapper) QueryTCCFenceDO(tx *sql.Tx, xid string, branchId int64) (*model.TCCFenceDO, error) { prepareStmt, err := tx.PrepareContext(context.Background(), sql2.GetQuerySQLByBranchIdAndXid(t.logTableName)) if err != nil { - return nil, errors.NewTccFenceError(errors.TccFenceDbError, "query tcc fence prepare sql failed", err) + return nil, fmt.Errorf("query tcc fence prepare sql failed, [%w]", err) } defer prepareStmt.Close() @@ -76,9 +75,9 @@ func (t *TccFenceStoreDatabaseMapper) QueryTCCFenceDO(tx *sql.Tx, xid string, br if err = result.Scan(&xid, &branchId, &actionName, &status, &gmtCreate, &gmtModify); err != nil { // will return error, if rows is empty if err.Error() == "sql: no rows in result set" { - return nil, errors.NewTccFenceError(errors.TccFenceDbError, "query tcc fence get scan row,no rows in result set", err) + return nil, fmt.Errorf("query tcc fence get scan row,no rows in result set, [%w]", err) } else { - return nil, errors.NewTccFenceError(errors.TccFenceDbError, "query tcc fence get scan row failed", err) + return nil, fmt.Errorf("query tcc fence get scan row failed, [%w]", err) } } @@ -96,7 +95,7 @@ func (t *TccFenceStoreDatabaseMapper) QueryTCCFenceDO(tx *sql.Tx, xid string, br func (t *TccFenceStoreDatabaseMapper) InsertTCCFenceDO(tx *sql.Tx, tccFenceDo *model.TCCFenceDO) error { prepareStmt, err := tx.PrepareContext(context.Background(), sql2.GetInsertLocalTCCLogSQL(t.logTableName)) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "insert tcc fence prepare sql failed", err) + return fmt.Errorf("insert tcc fence prepare sql failed, [%w]", err) } defer prepareStmt.Close() @@ -104,17 +103,15 @@ func (t *TccFenceStoreDatabaseMapper) InsertTCCFenceDO(tx *sql.Tx, tccFenceDo *m result, err := prepareStmt.Exec(tccFenceDo.Xid, tccFenceDo.BranchId, tccFenceDo.ActionName, tccFenceDo.Status, timeNow, timeNow) if err != nil { if mysqlError, ok := err.(*mysql.MySQLError); ok && mysqlError.Number == 1062 { - return errors.NewTccFenceError(errors.TccFenceDbDuplicateKeyError, - fmt.Sprintf("Insert tcc fence record duplicate key exception. xid= %s, branchId= %d", tccFenceDo.Xid, tccFenceDo.BranchId), - err) + return fmt.Errorf("insert tcc fence record duplicate key exception. xid= %s, branchId= %d, [%w]", tccFenceDo.Xid, tccFenceDo.BranchId, err) } else { - return errors.NewTccFenceError(errors.TccFenceDbError, "insert tcc fence exec sql failed", err) + return fmt.Errorf("insert tcc fence exec sql failed, [%w]", err) } } affected, err := result.RowsAffected() if err != nil || affected == 0 { - return errors.NewTccFenceError(errors.TccFenceDbError, "insert tcc fence get row affect failed", err) + return fmt.Errorf("insert tcc fence get affected rows failed, [%w]", err) } return nil @@ -123,18 +120,18 @@ func (t *TccFenceStoreDatabaseMapper) InsertTCCFenceDO(tx *sql.Tx, tccFenceDo *m func (t *TccFenceStoreDatabaseMapper) UpdateTCCFenceDO(tx *sql.Tx, xid string, branchId int64, oldStatus enum.FenceStatus, newStatus enum.FenceStatus) error { prepareStmt, err := tx.PrepareContext(context.Background(), sql2.GetUpdateStatusSQLByBranchIdAndXid(t.logTableName)) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "update tcc fence prepare sql failed", err) + return fmt.Errorf("update tcc fence prepare sql failed, [%w]", err) } defer prepareStmt.Close() result, err := prepareStmt.Exec(newStatus, time.Now(), xid, branchId, oldStatus) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "update tcc fence exec sql failed", err) + return fmt.Errorf("update tcc fence exec sql failed, [%w]", err) } affected, err := result.RowsAffected() if err != nil || affected == 0 { - return errors.NewTccFenceError(errors.TccFenceDbError, "update tcc fence get row affect failed", err) + return fmt.Errorf("update tcc fence get affected rows failed, [%w]", err) } return nil @@ -143,18 +140,18 @@ func (t *TccFenceStoreDatabaseMapper) UpdateTCCFenceDO(tx *sql.Tx, xid string, b func (t *TccFenceStoreDatabaseMapper) DeleteTCCFenceDO(tx *sql.Tx, xid string, branchId int64) error { prepareStmt, err := tx.PrepareContext(context.Background(), sql2.GetDeleteSQLByBranchIdAndXid(t.logTableName)) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence prepare sql failed ", err) + return fmt.Errorf("delete tcc fence prepare sql failed, [%w]", err) } defer prepareStmt.Close() result, err := prepareStmt.Exec(xid, branchId) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence execute sql failed", err) + return fmt.Errorf("delete tcc fence exec sql failed, [%w]", err) } affected, err := result.RowsAffected() if err != nil || affected == 0 { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence get rows affected failed", err) + return fmt.Errorf("delete tcc fence get affected rows failed, [%w]", err) } return nil @@ -163,18 +160,18 @@ func (t *TccFenceStoreDatabaseMapper) DeleteTCCFenceDO(tx *sql.Tx, xid string, b func (t *TccFenceStoreDatabaseMapper) DeleteTCCFenceDOByMdfDate(tx *sql.Tx, datetime time.Time) error { prepareStmt, err := tx.PrepareContext(context.Background(), sql2.GetDeleteSQLByMdfDateAndStatus(t.logTableName)) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence prepare sql failed", err) + return fmt.Errorf("delete tcc fence prepare sql failed, [%w]", err) } defer prepareStmt.Close() result, err := prepareStmt.Exec(datetime) if err != nil { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence exec sql failed", err) + return fmt.Errorf("delete tcc fence exec sql failed, [%w]", err) } affected, err := result.RowsAffected() if err != nil || affected == 0 { - return errors.NewTccFenceError(errors.TccFenceDbError, "delete tcc fence get rows affected failed", err) + return fmt.Errorf("delete tcc fence get affected rows failed, [%w]", err) } return nil diff --git a/pkg/rm/tcc/tcc_resource_test.go b/pkg/rm/tcc/tcc_resource_test.go index 729a4a924..051d1aa7e 100644 --- a/pkg/rm/tcc/tcc_resource_test.go +++ b/pkg/rm/tcc/tcc_resource_test.go @@ -23,7 +23,8 @@ import ( "reflect" "testing" - "github.com/agiledragon/gomonkey" + "github.com/agiledragon/gomonkey/v2" + "github.com/seata/seata-go/pkg/protocol/branch" "github.com/seata/seata-go/pkg/protocol/message" "github.com/seata/seata-go/pkg/remoting/getty" diff --git a/pkg/rm/tcc/tcc_service.go b/pkg/rm/tcc/tcc_service.go index 6d21fcd48..9694a32fa 100644 --- a/pkg/rm/tcc/tcc_service.go +++ b/pkg/rm/tcc/tcc_service.go @@ -20,13 +20,12 @@ package tcc import ( "context" "encoding/json" + "fmt" "reflect" "sync" "time" gostnet "github.com/dubbogo/gost/net" - "github.com/pkg/errors" - "github.com/seata/seata-go/pkg/constant" "github.com/seata/seata-go/pkg/protocol/branch" "github.com/seata/seata-go/pkg/rm" @@ -92,9 +91,9 @@ func (t *TCCServiceProxy) Prepare(ctx context.Context, params interface{}) (inte // registeBranch send register branch transaction request func (t *TCCServiceProxy) registeBranch(ctx context.Context, params interface{}) error { if !tm.IsGlobalTx(ctx) { - err := errors.New("BranchRegister error, transaction should be opened") - log.Errorf(err.Error()) - return err + errStr := "BranchRegister error, transaction should be opened" + log.Errorf(errStr) + return fmt.Errorf(errStr) } tccContext := t.initBusinessActionContext(ctx, params) diff --git a/pkg/rm/tcc/tcc_service_test.go b/pkg/rm/tcc/tcc_service_test.go index 3ccb93694..614137f97 100644 --- a/pkg/rm/tcc/tcc_service_test.go +++ b/pkg/rm/tcc/tcc_service_test.go @@ -26,7 +26,8 @@ import ( "testing" "time" - "github.com/agiledragon/gomonkey" + "github.com/agiledragon/gomonkey/v2" + gostnet "github.com/dubbogo/gost/net" "github.com/seata/seata-go/pkg/constant" "github.com/stretchr/testify/assert" diff --git a/pkg/rm/two_phase.go b/pkg/rm/two_phase.go index 8d7cf7c95..05c3e6e35 100644 --- a/pkg/rm/two_phase.go +++ b/pkg/rm/two_phase.go @@ -19,9 +19,9 @@ package rm import ( "context" + "fmt" "reflect" - "github.com/pkg/errors" "github.com/seata/seata-go/pkg/tm" ) @@ -164,7 +164,7 @@ func ParseTwoPhaseActionByInterface(v interface{}) (*TwoPhaseAction, error) { typeOf := valueOfElem.Type() k := typeOf.Kind() if k != reflect.Struct { - return nil, errors.New("param should be a struct, instead of a pointer") + return nil, fmt.Errorf("param should be a struct, instead of a pointer") } numField := typeOf.NumField() @@ -195,17 +195,17 @@ func ParseTwoPhaseActionByInterface(v interface{}) (*TwoPhaseAction, error) { } } if !hasPrepareMethodName { - return nil, errors.New("missing prepare method") + return nil, fmt.Errorf("missing prepare method") } if !hasCommitMethodName { - return nil, errors.New("missing commit method") + return nil, fmt.Errorf("missing commit method") } if !hasRollbackMethod { - return nil, errors.New("missing rollback method") + return nil, fmt.Errorf("missing rollback method") } twoPhaseName = getActionName(v) if twoPhaseName == "" { - return nil, errors.New("missing two phase name") + return nil, fmt.Errorf("missing two phase name") } result.actionName = twoPhaseName return &result, nil diff --git a/pkg/tm/global_transaction.go b/pkg/tm/global_transaction.go index 7943e0bdd..8ee554eee 100644 --- a/pkg/tm/global_transaction.go +++ b/pkg/tm/global_transaction.go @@ -19,6 +19,7 @@ package tm import ( "context" + "fmt" "sync" "time" @@ -60,7 +61,7 @@ func (g *GlobalTransactionManager) Begin(ctx context.Context, timeout time.Durat } if res == nil || res.(message.GlobalBeginResponse).ResultCode == message.ResultCodeFailed { log.Errorf("GlobalBeginRequest result is empty or result code is failed, res %v", res) - return errors.New("GlobalBeginRequest result is empty or result code is failed.") + return fmt.Errorf("GlobalBeginRequest result is empty or result code is failed.") } log.Infof("GlobalBeginRequest success, res %v", res) @@ -75,7 +76,7 @@ func (g *GlobalTransactionManager) Commit(ctx context.Context, gtr *GlobalTransa return nil } if gtr.Xid == "" { - return errors.New("Commit xid should not be empty") + return fmt.Errorf("Commit xid should not be empty") } bf := backoff.New(ctx, backoff.Config{ @@ -116,7 +117,7 @@ func (g *GlobalTransactionManager) Rollback(ctx context.Context, gtr *GlobalTran return nil } if gtr.Xid == "" { - return errors.New("Rollback xid should not be empty") + return fmt.Errorf("Rollback xid should not be empty") } bf := backoff.New(ctx, backoff.Config{ diff --git a/pkg/tm/global_transaction_test.go b/pkg/tm/global_transaction_test.go index dba76d0cc..d9c43ab52 100644 --- a/pkg/tm/global_transaction_test.go +++ b/pkg/tm/global_transaction_test.go @@ -23,10 +23,10 @@ import ( "testing" "time" - "github.com/seata/seata-go/pkg/util/log" + "github.com/agiledragon/gomonkey/v2" - "github.com/agiledragon/gomonkey" "github.com/pkg/errors" + "github.com/seata/seata-go/pkg/util/log" "github.com/stretchr/testify/assert" "github.com/seata/seata-go/pkg/protocol/message" diff --git a/pkg/tm/transaction_executor.go b/pkg/tm/transaction_executor.go index a1bdc0bbb..5937c92dc 100644 --- a/pkg/tm/transaction_executor.go +++ b/pkg/tm/transaction_executor.go @@ -42,11 +42,11 @@ type CallbackWithCtx func(ctx context.Context) error // WithGlobalTx begin a global transaction and make it step into committed or rollbacked status. func WithGlobalTx(ctx context.Context, gc *GtxConfig, business CallbackWithCtx) (re error) { if gc == nil { - return errors.New("global transaction config info is required.") + return fmt.Errorf("global transaction config info is required.") } if gc.Name == "" { - return errors.New("global transaction name is required.") + return fmt.Errorf("global transaction name is required.") } // open global transaction for the first time @@ -141,7 +141,7 @@ func begin(ctx context.Context, gc *GtxConfig) error { useExistGtx(ctx, gc) return nil } - return errors.New("no existing transaction found for transaction marked with pg 'mandatory'") + return fmt.Errorf("no existing transaction found for transaction marked with pg 'mandatory'") default: return fmt.Errorf("not supported propagation:%d", pg) } diff --git a/pkg/tm/transaction_executor_test.go b/pkg/tm/transaction_executor_test.go index fbb82f271..5b3f0d71d 100644 --- a/pkg/tm/transaction_executor_test.go +++ b/pkg/tm/transaction_executor_test.go @@ -24,9 +24,10 @@ import ( "testing" "time" + "github.com/agiledragon/gomonkey/v2" + "github.com/pkg/errors" - "github.com/agiledragon/gomonkey" "github.com/stretchr/testify/assert" "github.com/seata/seata-go/pkg/protocol/message" diff --git a/pkg/util/convert/convert.go b/pkg/util/convert/convert.go index 714c90329..4e48fac5e 100644 --- a/pkg/util/convert/convert.go +++ b/pkg/util/convert/convert.go @@ -209,7 +209,7 @@ func ConvertAssignRows(dest, src interface{}) error { dpv := reflect.ValueOf(dest) if dpv.Kind() != reflect.Ptr { - return errors.New("destination not a pointer") + return fmt.Errorf("destination not a pointer") } if dpv.IsNil() { return errNilPtr diff --git a/pkg/util/errors/error_code.go b/pkg/util/errors/code.go similarity index 64% rename from pkg/util/errors/error_code.go rename to pkg/util/errors/code.go index edf4628a7..dfe502059 100644 --- a/pkg/util/errors/error_code.go +++ b/pkg/util/errors/code.go @@ -21,83 +21,83 @@ type TransactionErrorCode int32 const ( // TransactionErrorCodeUnknown Unknown transaction errors code. - TransactionErrorCodeUnknown = TransactionErrorCode(0) + TransactionErrorCodeUnknown TransactionErrorCode = iota // TransactionErrorCodeBeginFailed BeginFailed - TransactionErrorCodeBeginFailed = TransactionErrorCode(1) + TransactionErrorCodeBeginFailed // TransactionErrorCodeLockKeyConflict Lock key conflict transaction errors code. - TransactionErrorCodeLockKeyConflict = TransactionErrorCode(2) + TransactionErrorCodeLockKeyConflict - // Io transaction errors code. - IO = TransactionErrorCode(3) + // TransactionErrorCodeIO transaction errors code. + TransactionErrorCodeIO // TransactionErrorCodeBranchRollbackFailedRetriable Branch rollback failed retriable transaction errors code. - TransactionErrorCodeBranchRollbackFailedRetriable = TransactionErrorCode(4) + TransactionErrorCodeBranchRollbackFailedRetriable // TransactionErrorCodeBranchRollbackFailedUnretriable Branch rollback failed unretriable transaction errors code. - TransactionErrorCodeBranchRollbackFailedUnretriable = TransactionErrorCode(5) + TransactionErrorCodeBranchRollbackFailedUnretriable // TransactionErrorCodeBranchRegisterFailed Branch register failed transaction errors code. - TransactionErrorCodeBranchRegisterFailed = TransactionErrorCode(6) + TransactionErrorCodeBranchRegisterFailed // TransactionErrorCodeBranchReportFailed Branch report failed transaction errors code. - TransactionErrorCodeBranchReportFailed = TransactionErrorCode(7) + TransactionErrorCodeBranchReportFailed // TransactionErrorCodeLockableCheckFailed Lockable check failed transaction errors code. - TransactionErrorCodeLockableCheckFailed = TransactionErrorCode(8) + TransactionErrorCodeLockableCheckFailed // TransactionErrorCodeBranchTransactionNotExist Branch transaction not exist transaction errors code. - TransactionErrorCodeBranchTransactionNotExist = TransactionErrorCode(9) + TransactionErrorCodeBranchTransactionNotExist // TransactionErrorCodeGlobalTransactionNotExist Global transaction not exist transaction errors code. - TransactionErrorCodeGlobalTransactionNotExist = TransactionErrorCode(10) + TransactionErrorCodeGlobalTransactionNotExist // TransactionErrorCodeGlobalTransactionNotActive Global transaction not active transaction errors code. - TransactionErrorCodeGlobalTransactionNotActive = TransactionErrorCode(11) + TransactionErrorCodeGlobalTransactionNotActive // TransactionErrorCodeGlobalTransactionStatusInvalid Global transaction status invalid transaction errors code. - TransactionErrorCodeGlobalTransactionStatusInvalid = TransactionErrorCode(12) + TransactionErrorCodeGlobalTransactionStatusInvalid // TransactionErrorCodeFailedToSendBranchCommitRequest Failed to send branch commit request transaction errors code. - TransactionErrorCodeFailedToSendBranchCommitRequest = TransactionErrorCode(13) + TransactionErrorCodeFailedToSendBranchCommitRequest // TransactionErrorCodeFailedToSendBranchRollbackRequest Failed to send branch rollback request transaction errors code. - TransactionErrorCodeFailedToSendBranchRollbackRequest = TransactionErrorCode(14) + TransactionErrorCodeFailedToSendBranchRollbackRequest // TransactionErrorCodeFailedToAddBranch Failed to add branch transaction errors code. - TransactionErrorCodeFailedToAddBranch = TransactionErrorCode(15) + TransactionErrorCodeFailedToAddBranch // TransactionErrorCodeFailedLockGlobalTranscation Failed to lock global transaction errors code. - TransactionErrorCodeFailedLockGlobalTranscation = TransactionErrorCode(16) + TransactionErrorCodeFailedLockGlobalTranscation // TransactionErrorCodeFailedWriteSession FailedWriteSession - TransactionErrorCodeFailedWriteSession = TransactionErrorCode(17) + TransactionErrorCodeFailedWriteSession // FailedStore Failed to holder errors code - FailedStore = TransactionErrorCode(18) + FailedStore // LockKeyConflictFailFast Lock key conflict fail fast transaction exception code. - LockKeyConflictFailFast = TransactionErrorCode(19) + LockKeyConflictFailFast // TccFenceDbDuplicateKeyError Insert tcc fence record duplicate key errors - TccFenceDbDuplicateKeyError = TransactionErrorCode(20) + TccFenceDbDuplicateKeyError // RollbackFenceError rollback tcc fence error - RollbackFenceError = TransactionErrorCode(21) + RollbackFenceError // CommitFenceError commit tcc fence error - CommitFenceError = TransactionErrorCode(22) + CommitFenceError // TccFenceDbError query tcc fence prepare sql failed - TccFenceDbError = TransactionErrorCode(23) + TccFenceDbError // PrepareFenceError prepare tcc fence error - PrepareFenceError = TransactionErrorCode(24) + PrepareFenceError // FenceBusinessError callback business method maybe return this error type - FenceBusinessError = TransactionErrorCode(26) + FenceBusinessError // FencePhaseError have fence phase but is not illegal value - FencePhaseError = TransactionErrorCode(27) + FencePhaseError ) diff --git a/pkg/util/errors/error.go b/pkg/util/errors/error.go index f1b6efd06..f04482466 100644 --- a/pkg/util/errors/error.go +++ b/pkg/util/errors/error.go @@ -19,36 +19,20 @@ package errors import ( "fmt" - - "github.com/pkg/errors" -) - -var ( - ErrorTooManySessions = errors.New("too many sessions") - ErrorHeartBeatTimeOut = errors.New("heart beat time out") ) -type TransactionError struct { - Code byte - Message string -} - -func (e TransactionError) Error() string { - return fmt.Sprintf("TransactionError code %d, msg %s", e.Code, e.Message) -} - -type TccFenceError struct { +type SeataError struct { Code TransactionErrorCode Message string Parent error } -func (e TccFenceError) Error() string { - return fmt.Sprintf("TccFenceError code %d, msg %s, parent msg is %s", e.Code, e.Message, e.Parent) +func (e SeataError) Error() string { + return fmt.Sprintf("SeataError code %d, msg %s, parent msg is %s", e.Code, e.Message, e.Parent) } -func NewTccFenceError(code TransactionErrorCode, msg string, parent error) *TccFenceError { - return &TccFenceError{ +func New(code TransactionErrorCode, msg string, parent error) *SeataError { + return &SeataError{ code, msg, parent, diff --git a/pkg/util/log/logging.go b/pkg/util/log/logging.go index 29e44eda3..3119eafa7 100644 --- a/pkg/util/log/logging.go +++ b/pkg/util/log/logging.go @@ -19,7 +19,6 @@ package log import ( "bytes" - "errors" "fmt" "time" @@ -52,7 +51,7 @@ const ( func (l *LogLevel) UnmarshalText(text []byte) error { if l == nil { - return errors.New("can't unmarshal a nil *Level") + return fmt.Errorf("can't unmarshal a nil *Level") } if !l.unmarshalText(text) && !l.unmarshalText(bytes.ToLower(text)) { return fmt.Errorf("unrecognized level: %q", text) diff --git a/sample/at/gin/client/main.go b/sample/at/gin/client/main.go index 94a2d98c3..7de7c763c 100644 --- a/sample/at/gin/client/main.go +++ b/sample/at/gin/client/main.go @@ -19,7 +19,6 @@ package main import ( "context" - "errors" "flag" "fmt" "net/http" @@ -60,7 +59,7 @@ func updateData(ctx context.Context) (re error) { Set(constant.XidKey, tm.GetXID(ctx)). End(func(response gorequest.Response, body string, errs []error) { if response.StatusCode != http.StatusOK { - re = errors.New("update data fail") + re = fmt.Errorf("update data fail") } }) return diff --git a/sample/at/rollback/client/main.go b/sample/at/rollback/client/main.go index 546dc0b31..d757a97f7 100644 --- a/sample/at/rollback/client/main.go +++ b/sample/at/rollback/client/main.go @@ -19,7 +19,6 @@ package main import ( "context" - "errors" "flag" "fmt" "net/http" @@ -63,7 +62,7 @@ func updateData(ctx context.Context) (re error) { Set(constant.XidKey, tm.GetXID(ctx)). End(func(response gorequest.Response, body string, errs []error) { if response.StatusCode != http.StatusOK { - re = errors.New("update data fail") + re = fmt.Errorf("update data fail") } }) @@ -71,7 +70,7 @@ func updateData(ctx context.Context) (re error) { Set(constant.XidKey, tm.GetXID(ctx)). End(func(response gorequest.Response, body string, errs1 []error) { if response.StatusCode != http.StatusOK { - re = errors.New("update data fail") + re = fmt.Errorf("update data fail") } }) return diff --git a/sample/at/rollback/server2/service.go b/sample/at/rollback/server2/service.go index 474d2bade..295d5f857 100644 --- a/sample/at/rollback/server2/service.go +++ b/sample/at/rollback/server2/service.go @@ -23,8 +23,6 @@ import ( "fmt" "time" - "github.com/pkg/errors" - sql2 "github.com/seata/seata-go/pkg/datasource/sql" ) @@ -55,7 +53,7 @@ func updateDataFail(ctx context.Context) error { } fmt.Printf("update success: %d.\n", rows) if rows == 0 { - return errors.New("rows affected 0") + return fmt.Errorf("rows affected 0") } return nil }