diff --git a/container/garray/garray_normal_any.go b/container/garray/garray_normal_any.go index 0e16736de..07b33c813 100644 --- a/container/garray/garray_normal_any.go +++ b/container/garray/garray_normal_any.go @@ -9,6 +9,7 @@ package garray import ( "bytes" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/empty" "github.com/gogf/gf/internal/json" @@ -123,7 +124,7 @@ func (a *Array) Set(index int, value interface{}) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } a.array[index] = value return nil @@ -176,7 +177,7 @@ func (a *Array) InsertBefore(index int, value interface{}) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]interface{}{}, a.array[index:]...) a.array = append(a.array[0:index], value) @@ -189,7 +190,7 @@ func (a *Array) InsertAfter(index int, value interface{}) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]interface{}{}, a.array[index+1:]...) a.array = append(a.array[0:index+1], value) @@ -545,7 +546,7 @@ func (a *Array) Fill(startIndex int, num int, value interface{}) error { a.mu.Lock() defer a.mu.Unlock() if startIndex < 0 || startIndex > len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) } for i := startIndex; i < startIndex+num; i++ { if i > len(a.array)-1 { diff --git a/container/garray/garray_normal_int.go b/container/garray/garray_normal_int.go index 44e577383..ee3d173ba 100644 --- a/container/garray/garray_normal_int.go +++ b/container/garray/garray_normal_int.go @@ -9,6 +9,7 @@ package garray import ( "bytes" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "math" @@ -104,7 +105,7 @@ func (a *IntArray) Set(index int, value int) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } a.array[index] = value return nil @@ -172,7 +173,7 @@ func (a *IntArray) InsertBefore(index int, value int) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]int{}, a.array[index:]...) a.array = append(a.array[0:index], value) @@ -185,7 +186,7 @@ func (a *IntArray) InsertAfter(index int, value int) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]int{}, a.array[index+1:]...) a.array = append(a.array[0:index+1], value) @@ -556,7 +557,7 @@ func (a *IntArray) Fill(startIndex int, num int, value int) error { a.mu.Lock() defer a.mu.Unlock() if startIndex < 0 || startIndex > len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) } for i := startIndex; i < startIndex+num; i++ { if i > len(a.array)-1 { diff --git a/container/garray/garray_normal_str.go b/container/garray/garray_normal_str.go index 61fd0e8d0..11cb6551b 100644 --- a/container/garray/garray_normal_str.go +++ b/container/garray/garray_normal_str.go @@ -8,6 +8,7 @@ package garray import ( "bytes" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "github.com/gogf/gf/text/gstr" @@ -90,7 +91,7 @@ func (a *StrArray) Set(index int, value string) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } a.array[index] = value return nil @@ -159,7 +160,7 @@ func (a *StrArray) InsertBefore(index int, value string) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]string{}, a.array[index:]...) a.array = append(a.array[0:index], value) @@ -172,7 +173,7 @@ func (a *StrArray) InsertAfter(index int, value string) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } rear := append([]string{}, a.array[index+1:]...) a.array = append(a.array[0:index+1], value) @@ -559,7 +560,7 @@ func (a *StrArray) Fill(startIndex int, num int, value string) error { a.mu.Lock() defer a.mu.Unlock() if startIndex < 0 || startIndex > len(a.array) { - return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) + return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) } for i := startIndex; i < startIndex+num; i++ { if i > len(a.array)-1 { diff --git a/container/gpool/gpool.go b/container/gpool/gpool.go index 0022cfb28..4b7e5e583 100644 --- a/container/gpool/gpool.go +++ b/container/gpool/gpool.go @@ -8,6 +8,7 @@ package gpool import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "time" @@ -66,7 +67,7 @@ func New(ttl time.Duration, newFunc NewFunc, expireFunc ...ExpireFunc) *Pool { // Put puts an item to pool. func (p *Pool) Put(value interface{}) error { if p.closed.Val() { - return gerror.NewCode(gerror.CodeInvalidOperation, "pool is closed") + return gerror.NewCode(gcode.CodeInvalidOperation, "pool is closed") } item := &poolItem{ value: value, @@ -117,7 +118,7 @@ func (p *Pool) Get() (interface{}, error) { if p.NewFunc != nil { return p.NewFunc() } - return nil, gerror.NewCode(gerror.CodeInvalidOperation, "pool is empty") + return nil, gerror.NewCode(gcode.CodeInvalidOperation, "pool is empty") } // Size returns the count of available items of pool. diff --git a/crypto/gaes/gaes.go b/crypto/gaes/gaes.go index 2fba47c19..43bc0600a 100644 --- a/crypto/gaes/gaes.go +++ b/crypto/gaes/gaes.go @@ -11,6 +11,7 @@ import ( "bytes" "crypto/aes" "crypto/cipher" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" ) @@ -63,7 +64,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv ...[]byte) ([]byte, error) { } blockSize := block.BlockSize() if len(cipherText) < blockSize { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText too short") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "cipherText too short") } ivValue := ([]byte)(nil) if len(iv) > 0 { @@ -72,7 +73,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv ...[]byte) ([]byte, error) { ivValue = []byte(IVDefaultValue) } if len(cipherText)%blockSize != 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText is not a multiple of the block size") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "cipherText is not a multiple of the block size") } blockModel := cipher.NewCBCDecrypter(block, ivValue) plainText := make([]byte, len(cipherText)) @@ -93,22 +94,22 @@ func PKCS5Padding(src []byte, blockSize int) []byte { func PKCS5UnPadding(src []byte, blockSize int) ([]byte, error) { length := len(src) if blockSize <= 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid blocklen") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "invalid blocklen") } if length%blockSize != 0 || length == 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid data len") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "invalid data len") } unpadding := int(src[length-1]) if unpadding > blockSize || unpadding == 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid padding") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "invalid padding") } padding := src[length-unpadding:] for i := 0; i < unpadding; i++ { if padding[i] != byte(unpadding) { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid padding") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "invalid padding") } } @@ -146,7 +147,7 @@ func DecryptCFB(cipherText []byte, key []byte, unPadding int, iv ...[]byte) ([]b return nil, err } if len(cipherText) < aes.BlockSize { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText too short") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "cipherText too short") } ivValue := ([]byte)(nil) if len(iv) > 0 { diff --git a/crypto/gdes/gdes.go b/crypto/gdes/gdes.go index e12113719..00d030e75 100644 --- a/crypto/gdes/gdes.go +++ b/crypto/gdes/gdes.go @@ -66,7 +66,7 @@ func DecryptECB(cipherText []byte, key []byte, padding int) ([]byte, error) { // The length of the should be either 16 or 24 bytes. func EncryptECBTriple(plainText []byte, key []byte, padding int) ([]byte, error) { if len(key) != 16 && len(key) != 24 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length error") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "key length error") } text, err := Padding(plainText, padding) @@ -100,7 +100,7 @@ func EncryptECBTriple(plainText []byte, key []byte, padding int) ([]byte, error) // The length of the should be either 16 or 24 bytes. func DecryptECBTriple(cipherText []byte, key []byte, padding int) ([]byte, error) { if len(key) != 16 && len(key) != 24 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length error") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "key length error") } var newKey []byte @@ -138,7 +138,7 @@ func EncryptCBC(plainText []byte, key []byte, iv []byte, padding int) ([]byte, e } if len(iv) != block.BlockSize() { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "iv length invalid") } text, err := Padding(plainText, padding) @@ -161,7 +161,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv []byte, padding int) ([]byte, } if len(iv) != block.BlockSize() { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "iv length invalid") } text := make([]byte, len(cipherText)) @@ -179,7 +179,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv []byte, padding int) ([]byte, // EncryptCBCTriple encrypts using TripleDES and CBC mode. func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]byte, error) { if len(key) != 16 && len(key) != 24 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "key length invalid") } var newKey []byte @@ -196,7 +196,7 @@ func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]b } if len(iv) != block.BlockSize() { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "iv length invalid") } text, err := Padding(plainText, padding) @@ -214,7 +214,7 @@ func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]b // DecryptCBCTriple decrypts <cipherText> using TripleDES and CBC mode. func DecryptCBCTriple(cipherText []byte, key []byte, iv []byte, padding int) ([]byte, error) { if len(key) != 16 && len(key) != 24 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "key length invalid") } var newKey []byte @@ -231,7 +231,7 @@ func DecryptCBCTriple(cipherText []byte, key []byte, iv []byte, padding int) ([] } if len(iv) != block.BlockSize() { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "iv length invalid") } text := make([]byte, len(cipherText)) @@ -262,12 +262,12 @@ func Padding(text []byte, padding int) ([]byte, error) { switch padding { case NOPADDING: if len(text)%8 != 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "text length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "text length invalid") } case PKCS5PADDING: return PaddingPKCS5(text, 8), nil default: - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "padding type error") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "padding type error") } return text, nil @@ -277,12 +277,12 @@ func UnPadding(text []byte, padding int) ([]byte, error) { switch padding { case NOPADDING: if len(text)%8 != 0 { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "text length invalid") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "text length invalid") } case PKCS5PADDING: return UnPaddingPKCS5(text), nil default: - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "padding type error") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "padding type error") } return text, nil } diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index 030d9a336..49dd32c3a 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -10,6 +10,7 @@ package gdb import ( "context" "database/sql" + "github.com/gogf/gf/errors/gcode" "time" "github.com/gogf/gf/errors/gerror" @@ -336,7 +337,7 @@ func New(group ...string) (db DB, err error) { if len(configs.config) < 1 { return nil, gerror.NewCode( - gerror.CodeInvalidConfiguration, + gcode.CodeInvalidConfiguration, "database configuration is empty, please set the database configuration before using", ) } @@ -358,7 +359,7 @@ func New(group ...string) (db DB, err error) { return c.db, nil } else { return nil, gerror.NewCodef( - gerror.CodeInvalidConfiguration, + gcode.CodeInvalidConfiguration, `cannot find database driver for specified database type "%s", did you misspell type name "%s" or forget importing the database driver?`, node.Type, node.Type, ) @@ -368,7 +369,7 @@ func New(group ...string) (db DB, err error) { } } else { return nil, gerror.NewCodef( - gerror.CodeInvalidConfiguration, + gcode.CodeInvalidConfiguration, `database configuration node "%s" is not found, did you misspell group name "%s" or miss the database configuration?`, groupName, groupName, ) @@ -411,7 +412,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) { } } if len(masterList) < 1 { - return nil, gerror.NewCode(gerror.CodeInvalidConfiguration, "at least one master node configuration's need to make sense") + return nil, gerror.NewCode(gcode.CodeInvalidConfiguration, "at least one master node configuration's need to make sense") } if len(slaveList) < 1 { slaveList = masterList @@ -422,7 +423,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) { return getConfigNodeByWeight(slaveList), nil } } else { - return nil, gerror.NewCodef(gerror.CodeInvalidConfiguration, "empty database configuration for item name '%s'", group) + return nil, gerror.NewCodef(gcode.CodeInvalidConfiguration, "empty database configuration for item name '%s'", group) } } diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 48512fc39..34954d65b 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -11,6 +11,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "reflect" "strings" @@ -89,7 +90,7 @@ func (c *Core) GetCtxTimeout(timeoutType int, ctx context.Context) (context.Cont return context.WithTimeout(ctx, c.db.GetConfig().PrepareTimeout) } default: - panic(gerror.NewCodef(gerror.CodeInvalidParameter, "invalid context timeout type: %d", timeoutType)) + panic(gerror.NewCodef(gcode.CodeInvalidParameter, "invalid context timeout type: %d", timeoutType)) } return ctx, func() {} } @@ -552,7 +553,7 @@ func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data inter updates = gconv.String(data) } if len(updates) == 0 { - return nil, gerror.NewCode(gerror.CodeMissingParameter, "data cannot be empty") + return nil, gerror.NewCode(gcode.CodeMissingParameter, "data cannot be empty") } if len(params) > 0 { args = append(params, args...) diff --git a/database/gdb/gdb_core_underlying.go b/database/gdb/gdb_core_underlying.go index 80dd32d58..8e88d0938 100644 --- a/database/gdb/gdb_core_underlying.go +++ b/database/gdb/gdb_core_underlying.go @@ -10,6 +10,7 @@ package gdb import ( "context" "database/sql" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gtime" @@ -136,7 +137,7 @@ func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interf func (c *Core) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) { if c.db.GetConfig().CtxStrict { if v := ctx.Value(ctxStrictKeyName); v == nil { - return sql, args, gerror.NewCode(gerror.CodeMissingParameter, ctxStrictErrorStr) + return sql, args, gerror.NewCode(gcode.CodeMissingParameter, ctxStrictErrorStr) } } return sql, args, nil @@ -181,7 +182,7 @@ func (c *Core) DoPrepare(ctx context.Context, link Link, sql string) (*Stmt, err if c.db.GetConfig().CtxStrict { if v := ctx.Value(ctxStrictKeyName); v == nil { - return nil, gerror.NewCode(gerror.CodeMissingParameter, ctxStrictErrorStr) + return nil, gerror.NewCode(gcode.CodeMissingParameter, ctxStrictErrorStr) } } diff --git a/database/gdb/gdb_driver_mssql.go b/database/gdb/gdb_driver_mssql.go index c5ac9be8a..48a83590e 100644 --- a/database/gdb/gdb_driver_mssql.go +++ b/database/gdb/gdb_driver_mssql.go @@ -15,6 +15,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "strconv" "strings" @@ -214,7 +215,7 @@ func (d *DriverMssql) TableFields(ctx context.Context, table string, schema ...s charL, charR := d.GetChars() table = gstr.Trim(table, charL+charR) if gstr.Contains(table, " ") { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations") } useSchema := d.db.GetSchema() if len(schema) > 0 && schema[0] != "" { @@ -292,10 +293,10 @@ ORDER BY a.id,a.colorder`, func (d *DriverMssql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) { switch option.InsertOption { case insertOptionSave: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by mssql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Save operation is not supported by mssql driver`) case insertOptionReplace: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by mssql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Replace operation is not supported by mssql driver`) default: return d.Core.DoInsert(ctx, link, table, list, option) diff --git a/database/gdb/gdb_driver_mysql.go b/database/gdb/gdb_driver_mysql.go index d4c5e53f0..251c37aed 100644 --- a/database/gdb/gdb_driver_mysql.go +++ b/database/gdb/gdb_driver_mysql.go @@ -10,6 +10,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "net/url" "github.com/gogf/gf/errors/gerror" @@ -121,7 +122,7 @@ func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...s charL, charR := d.GetChars() table = gstr.Trim(table, charL+charR) if gstr.Contains(table, " ") { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations") } useSchema := d.schema.Val() if len(schema) > 0 && schema[0] != "" { diff --git a/database/gdb/gdb_driver_oracle.go b/database/gdb/gdb_driver_oracle.go index d42cd1974..d3e3d157e 100644 --- a/database/gdb/gdb_driver_oracle.go +++ b/database/gdb/gdb_driver_oracle.go @@ -15,6 +15,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "reflect" "strconv" "strings" @@ -186,7 +187,7 @@ func (d *DriverOracle) TableFields(ctx context.Context, table string, schema ... charL, charR := d.GetChars() table = gstr.Trim(table, charL+charR) if gstr.Contains(table, " ") { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations") } useSchema := d.db.GetSchema() if len(schema) > 0 && schema[0] != "" { @@ -278,10 +279,10 @@ func (d *DriverOracle) getTableUniqueIndex(table string) (fields map[string]map[ func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) { switch option.InsertOption { case insertOptionSave: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by mssql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Save operation is not supported by mssql driver`) case insertOptionReplace: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by mssql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Replace operation is not supported by mssql driver`) } var ( diff --git a/database/gdb/gdb_driver_pgsql.go b/database/gdb/gdb_driver_pgsql.go index 07a8029fc..c0dbab9c9 100644 --- a/database/gdb/gdb_driver_pgsql.go +++ b/database/gdb/gdb_driver_pgsql.go @@ -15,6 +15,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "strings" "github.com/gogf/gf/errors/gerror" @@ -126,7 +127,7 @@ func (d *DriverPgsql) TableFields(ctx context.Context, table string, schema ...s charL, charR := d.GetChars() table = gstr.Trim(table, charL+charR) if gstr.Contains(table, " ") { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations") } table, _ = gregex.ReplaceString("\"", "", table) useSchema := d.db.GetSchema() @@ -190,10 +191,10 @@ ORDER BY a.attnum`, func (d *DriverPgsql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) { switch option.InsertOption { case insertOptionSave: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by pgsql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Save operation is not supported by pgsql driver`) case insertOptionReplace: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by pgsql driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Replace operation is not supported by pgsql driver`) default: return d.Core.DoInsert(ctx, link, table, list, option) diff --git a/database/gdb/gdb_driver_sqlite.go b/database/gdb/gdb_driver_sqlite.go index 61703aa43..405a391a8 100644 --- a/database/gdb/gdb_driver_sqlite.go +++ b/database/gdb/gdb_driver_sqlite.go @@ -14,6 +14,7 @@ import ( "context" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "strings" "github.com/gogf/gf/errors/gerror" @@ -99,7 +100,7 @@ func (d *DriverSqlite) TableFields(ctx context.Context, table string, schema ... charL, charR := d.GetChars() table = gstr.Trim(table, charL+charR) if gstr.Contains(table, " ") { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations") } useSchema := d.db.GetSchema() if len(schema) > 0 && schema[0] != "" { @@ -141,10 +142,10 @@ func (d *DriverSqlite) TableFields(ctx context.Context, table string, schema ... func (d *DriverSqlite) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) { switch option.InsertOption { case insertOptionSave: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by sqlite driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Save operation is not supported by sqlite driver`) case insertOptionReplace: - return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by sqlite driver`) + return nil, gerror.NewCode(gcode.CodeNotSupported, `Replace operation is not supported by sqlite driver`) default: return d.Core.DoInsert(ctx, link, table, list, option) diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index 1468cca3e..37ae7a8c3 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -10,6 +10,7 @@ import ( "bytes" "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "reflect" "regexp" "strings" @@ -776,7 +777,7 @@ func handleArguments(sql string, args []interface{}) (newSql string, newArgs []i // formatError customizes and returns the SQL error. func formatError(err error, s string, args ...interface{}) error { if err != nil && err != sql.ErrNoRows { - return gerror.NewCodef(gerror.CodeDbOperationError, "%s, %s\n", err.Error(), FormatSqlWithArgs(s, args)) + return gerror.NewCodef(gcode.CodeDbOperationError, "%s, %s\n", err.Error(), FormatSqlWithArgs(s, args)) } return err } diff --git a/database/gdb/gdb_model_delete.go b/database/gdb/gdb_model_delete.go index 43af4544c..b3f264f7d 100644 --- a/database/gdb/gdb_model_delete.go +++ b/database/gdb/gdb_model_delete.go @@ -9,6 +9,7 @@ package gdb import ( "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gtime" @@ -44,7 +45,7 @@ func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) { } conditionStr := conditionWhere + conditionExtra if !gstr.ContainsI(conditionStr, " WHERE ") { - return nil, gerror.NewCode(gerror.CodeMissingParameter, "there should be WHERE condition statement for DELETE operation") + return nil, gerror.NewCode(gcode.CodeMissingParameter, "there should be WHERE condition statement for DELETE operation") } return m.db.DoDelete(m.GetCtx(), m.getLink(true), m.tables, conditionStr, conditionArgs...) } diff --git a/database/gdb/gdb_model_insert.go b/database/gdb/gdb_model_insert.go index 90250c81b..5c40a7eba 100644 --- a/database/gdb/gdb_model_insert.go +++ b/database/gdb/gdb_model_insert.go @@ -9,6 +9,7 @@ package gdb import ( "database/sql" "github.com/gogf/gf/container/gset" + "github.com/gogf/gf/errors/gcode" "reflect" "github.com/gogf/gf/errors/gerror" @@ -210,7 +211,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err } }() if m.data == nil { - return nil, gerror.NewCode(gerror.CodeMissingParameter, "inserting into table with empty data") + return nil, gerror.NewCode(gcode.CodeMissingParameter, "inserting into table with empty data") } var ( list List @@ -274,12 +275,12 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err } default: - return result, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported list type:%v", kind) + return result, gerror.NewCodef(gcode.CodeInvalidParameter, "unsupported list type:%v", kind) } } if len(list) < 1 { - return result, gerror.NewCode(gerror.CodeMissingParameter, "data list cannot be empty") + return result, gerror.NewCode(gcode.CodeMissingParameter, "data list cannot be empty") } // Automatic handling for creating/updating time. @@ -364,7 +365,7 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op default: return option, gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `unsupported OnDuplicate parameter type "%s"`, reflect.TypeOf(m.onDuplicate), ) @@ -408,7 +409,7 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er default: return nil, gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `unsupported OnDuplicateEx parameter type "%s"`, reflect.TypeOf(onDuplicateEx), ) diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index 78fc25735..eefbec99b 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -8,6 +8,7 @@ package gdb import ( "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "reflect" @@ -316,7 +317,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error { reflectKind = reflectValue.Kind() if reflectKind != reflect.Ptr { - return gerror.NewCode(gerror.CodeInvalidParameter, `the parameter "pointer" for function Scan should type of pointer`) + return gerror.NewCode(gcode.CodeInvalidParameter, `the parameter "pointer" for function Scan should type of pointer`) } for reflectKind == reflect.Ptr { reflectValue = reflectValue.Elem() @@ -332,7 +333,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error { default: return gerror.NewCode( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `element of parameter "pointer" for function Scan should type of struct/*struct/[]struct/[]*struct`, ) } diff --git a/database/gdb/gdb_model_update.go b/database/gdb/gdb_model_update.go index 12f2ab492..4826b4d43 100644 --- a/database/gdb/gdb_model_update.go +++ b/database/gdb/gdb_model_update.go @@ -9,6 +9,7 @@ package gdb import ( "database/sql" "fmt" + "github.com/gogf/gf/errors/gcode" "reflect" "github.com/gogf/gf/errors/gerror" @@ -38,7 +39,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro } }() if m.data == nil { - return nil, gerror.NewCode(gerror.CodeMissingParameter, "updating table with empty data") + return nil, gerror.NewCode(gcode.CodeMissingParameter, "updating table with empty data") } var ( updateData = m.data @@ -76,7 +77,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro } conditionStr := conditionWhere + conditionExtra if !gstr.ContainsI(conditionStr, " WHERE ") { - return nil, gerror.NewCode(gerror.CodeMissingParameter, "there should be WHERE condition statement for UPDATE operation") + return nil, gerror.NewCode(gcode.CodeMissingParameter, "there should be WHERE condition statement for UPDATE operation") } return m.db.DoUpdate( m.GetCtx(), diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index 52ae7d617..542f302a9 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -8,6 +8,7 @@ package gdb import ( "fmt" + "github.com/gogf/gf/errors/gcode" "reflect" "github.com/gogf/gf/errors/gerror" @@ -124,7 +125,7 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { } if relatedFieldValue == nil { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `cannot find the related value of attribute name "%s" in with tag "%s" for attribute "%s.%s"`, relatedAttrName, parsedTagOutput.With, reflect.TypeOf(pointer).Elem(), field.Name(), ) @@ -239,7 +240,7 @@ func (m *Model) doWithScanStructs(pointer interface{}) error { } if relatedFieldValue == nil { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `cannot find the related value for attribute name "%s" of with tag "%s"`, relatedAttrName, parsedTagOutput.With, ) diff --git a/database/gdb/gdb_statement.go b/database/gdb/gdb_statement.go index 9bca2980f..24f755eb7 100644 --- a/database/gdb/gdb_statement.go +++ b/database/gdb/gdb_statement.go @@ -9,6 +9,7 @@ package gdb import ( "context" "database/sql" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gtime" @@ -59,7 +60,7 @@ func (s *Stmt) doStmtCommit(ctx context.Context, stmtType string, args ...interf result = s.Stmt.QueryRowContext(ctx, args...) default: - panic(gerror.NewCodef(gerror.CodeInvalidParameter, `invalid stmtType: %s`, stmtType)) + panic(gerror.NewCodef(gcode.CodeInvalidParameter, `invalid stmtType: %s`, stmtType)) } var ( timestampMilli2 = gtime.TimestampMilli() diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index ee738ad11..4468c3bad 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -8,6 +8,7 @@ package gdb import ( "database/sql" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/text/gstr" "github.com/gogf/gf/util/gconv" @@ -55,7 +56,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } // Necessary checks for parameters. if bindToAttrName == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, `bindToAttrName should not be empty`) + return gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`) } var ( @@ -67,12 +68,12 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr reflectKind = reflectValue.Kind() } if reflectKind != reflect.Ptr { - return gerror.NewCodef(gerror.CodeInvalidParameter, "listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind) } reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() if reflectKind != reflect.Slice && reflectKind != reflect.Array { - return gerror.NewCodef(gerror.CodeInvalidParameter, "listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind) } length := len(result) if length == 0 { @@ -136,7 +137,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr relationBindToSubAttrName = array[1] if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationResultFieldName); key == "" { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `cannot find possible related table field name "%s" from given relation key "%s"`, relationResultFieldName, relationKVStr, @@ -145,14 +146,14 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr relationResultFieldName = key } } else { - return gerror.NewCode(gerror.CodeInvalidParameter, `parameter relationKV should be format of "ResultFieldName:BindToAttrName"`) + return gerror.NewCode(gcode.CodeInvalidParameter, `parameter relationKV should be format of "ResultFieldName:BindToAttrName"`) } if relationResultFieldName != "" { // Note that the value might be type of slice. relationDataMap = result.MapKeyValue(relationResultFieldName) } if len(relationDataMap) == 0 { - return gerror.NewCodef(gerror.CodeInvalidParameter, `cannot find the relation data map, maybe invalid relation given "%v"`, relationKV) + return gerror.NewCodef(gcode.CodeInvalidParameter, `cannot find the relation data map, maybe invalid relation given "%v"`, relationKV) } } // Bind to target attribute. @@ -166,7 +167,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr if arrayItemType.Kind() == reflect.Ptr { if bindToAttrField, ok = arrayItemType.Elem().FieldByName(bindToAttrName); !ok { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, bindToAttrName, ) @@ -174,7 +175,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } else { if bindToAttrField, ok = arrayItemType.FieldByName(bindToAttrName); !ok { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, bindToAttrName, ) @@ -219,7 +220,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr relationFromAttrValue = arrayElemValue } if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() { - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) } // Check and find possible bind to attribute name. if relationKVStr != "" && !relationBindToSubAttrNameChecked { @@ -234,7 +235,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } if key, _ := gutil.MapPossibleItemByKey(filedMap, relationBindToSubAttrName); key == "" { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `cannot find possible related attribute name "%s" from given relation key "%s"`, relationBindToSubAttrName, relationKVStr, @@ -265,11 +266,11 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } } else { // May be the attribute does not exist yet. - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) } } else { return gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `relationKey should not be empty as field "%s" is slice`, bindToAttrName, ) @@ -301,7 +302,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } } else { // May be the attribute does not exist yet. - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) } } else { if i >= len(result) { @@ -345,7 +346,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } } else { // May be the attribute does not exist yet. - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV) } } else { if i >= len(result) { @@ -369,7 +370,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr } default: - return gerror.NewCodef(gerror.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String()) + return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String()) } } reflect.ValueOf(listPointer).Elem().Set(arrayValue) diff --git a/database/gdb/gdb_z_mysql_struct_test.go b/database/gdb/gdb_z_mysql_struct_test.go index 9f56f4772..5f12869a2 100644 --- a/database/gdb/gdb_z_mysql_struct_test.go +++ b/database/gdb/gdb_z_mysql_struct_test.go @@ -9,6 +9,7 @@ package gdb_test import ( "database/sql" "github.com/gogf/gf/database/gdb" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/gtime" @@ -408,7 +409,7 @@ func (user *User) UnmarshalValue(value interface{}) error { } return nil } - return gerror.NewCodef(gerror.CodeInvalidParameter, `unsupported value type for UnmarshalValue: %v`, reflect.TypeOf(value)) + return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported value type for UnmarshalValue: %v`, reflect.TypeOf(value)) } func Test_Model_Scan_UnmarshalValue(t *testing.T) { diff --git a/database/gredis/gredis_config.go b/database/gredis/gredis_config.go index e39a96ddb..e6fcae37e 100644 --- a/database/gredis/gredis_config.go +++ b/database/gredis/gredis_config.go @@ -8,6 +8,7 @@ package gredis import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" @@ -114,7 +115,7 @@ func ConfigFromStr(str string) (config *Config, err error) { config.Port = DefaultRedisPort } } else { - err = gerror.NewCodef(gerror.CodeInvalidConfiguration, `invalid redis configuration: "%s"`, str) + err = gerror.NewCodef(gcode.CodeInvalidConfiguration, `invalid redis configuration: "%s"`, str) } return } diff --git a/database/gredis/gredis_conn.go b/database/gredis/gredis_conn.go index ed5f90851..a56e9ddd7 100644 --- a/database/gredis/gredis_conn.go +++ b/database/gredis/gredis_conn.go @@ -9,6 +9,7 @@ package gredis import ( "context" "github.com/gogf/gf/container/gvar" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "github.com/gogf/gf/os/gtime" @@ -50,7 +51,7 @@ func (c *Conn) do(timeout time.Duration, commandName string, args ...interface{} if timeout > 0 { conn, ok := c.Conn.(redis.ConnWithTimeout) if !ok { - return gvar.New(nil), gerror.NewCode(gerror.CodeNotSupported, `current connection does not support "ConnWithTimeout"`) + return gvar.New(nil), gerror.NewCode(gcode.CodeNotSupported, `current connection does not support "ConnWithTimeout"`) } return conn.DoWithTimeout(timeout, commandName, args...) } @@ -107,7 +108,7 @@ func (c *Conn) ReceiveVar() (*gvar.Var, error) { func (c *Conn) ReceiveVarWithTimeout(timeout time.Duration) (*gvar.Var, error) { conn, ok := c.Conn.(redis.ConnWithTimeout) if !ok { - return gvar.New(nil), gerror.NewCode(gerror.CodeNotSupported, `current connection does not support "ConnWithTimeout"`) + return gvar.New(nil), gerror.NewCode(gcode.CodeNotSupported, `current connection does not support "ConnWithTimeout"`) } return resultToVar(conn.ReceiveWithTimeout(timeout)) } diff --git a/encoding/gcharset/gcharset.go b/encoding/gcharset/gcharset.go index af4998fc4..5d8137087 100644 --- a/encoding/gcharset/gcharset.go +++ b/encoding/gcharset/gcharset.go @@ -21,6 +21,7 @@ package gcharset import ( "bytes" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "io/ioutil" @@ -59,11 +60,11 @@ func Convert(dstCharset string, srcCharset string, src string) (dst string, err transform.NewReader(bytes.NewReader([]byte(src)), e.NewDecoder()), ) if err != nil { - return "", gerror.WrapCodef(gerror.CodeInternalError, err, "%s to utf8 failed", srcCharset) + return "", gerror.WrapCodef(gcode.CodeInternalError, err, "%s to utf8 failed", srcCharset) } src = string(tmp) } else { - return dst, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported srcCharset: %s", srcCharset) + return dst, gerror.NewCodef(gcode.CodeInvalidParameter, "unsupported srcCharset: %s", srcCharset) } } // Do the converting from UTF-8 to <dstCharset>. @@ -73,11 +74,11 @@ func Convert(dstCharset string, srcCharset string, src string) (dst string, err transform.NewReader(bytes.NewReader([]byte(src)), e.NewEncoder()), ) if err != nil { - return "", gerror.WrapCodef(gerror.CodeInternalError, err, "utf to %s failed", dstCharset) + return "", gerror.WrapCodef(gcode.CodeInternalError, err, "utf to %s failed", dstCharset) } dst = string(tmp) } else { - return dst, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported dstCharset: %s", dstCharset) + return dst, gerror.NewCodef(gcode.CodeInvalidParameter, "unsupported dstCharset: %s", dstCharset) } } else { dst = src diff --git a/encoding/gini/gini.go b/encoding/gini/gini.go index 43ae110da..0ff476b46 100644 --- a/encoding/gini/gini.go +++ b/encoding/gini/gini.go @@ -11,6 +11,7 @@ import ( "bufio" "bytes" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "io" @@ -70,7 +71,7 @@ func Decode(data []byte) (res map[string]interface{}, err error) { } if haveSection == false { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "failed to parse INI file, section not found") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "failed to parse INI file, section not found") } return res, nil } diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 9c6c46130..f9b5c673b 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -9,6 +9,7 @@ package gjson import ( "bytes" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "reflect" @@ -264,7 +265,7 @@ func doLoadContentWithOptions(dataType string, data []byte, options Options) (*J return nil, err } default: - err = gerror.NewCode(gerror.CodeInvalidParameter, "unsupported type for loading") + err = gerror.NewCode(gcode.CodeInvalidParameter, "unsupported type for loading") } if err != nil { return nil, err diff --git a/errors/gcode/gcode.go b/errors/gcode/gcode.go new file mode 100644 index 000000000..6248ed0c7 --- /dev/null +++ b/errors/gcode/gcode.go @@ -0,0 +1,95 @@ +// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +// Package gcode provides universal error code definition and common error codes implements. +package gcode + +import "fmt" + +// Code is universal error code interface definition. +type Code interface { + // Code returns the integer number of current error code. + Code() int + + // Message returns the brief message for current error code. + Message() string + + // Detail returns the detailed information of current error code, + // which is mainly designed as an extension field for error code. + Detail() interface{} +} + +// localCode is an implementer for interface Code for internal usage only. +type localCode struct { + code int // Error code, usually an integer. + message string // Brief message for this error code. + detail interface{} // As type of interface, it is mainly designed as an extension field for error code. +} + +// ================================================================================================================ +// Common error code definition. +// There are reserved internal error code by framework: code < 1000. +// ================================================================================================================ + +var ( + CodeNil = localCode{-1, "", nil} // No error code specified. + CodeOK = localCode{0, "OK", nil} // It is OK. + CodeInternalError = localCode{50, "Internal Error", nil} // An error occurred internally. + CodeValidationFailed = localCode{51, "Validation Failed", nil} // Data validation failed. + CodeDbOperationError = localCode{52, "Database Operation Error", nil} // Database operation error. + CodeInvalidParameter = localCode{53, "Invalid Parameter", nil} // The given parameter for current operation is invalid. + CodeMissingParameter = localCode{54, "Missing Parameter", nil} // Parameter for current operation is missing. + CodeInvalidOperation = localCode{55, "Invalid Operation", nil} // The function cannot be used like this. + CodeInvalidConfiguration = localCode{56, "Invalid Configuration", nil} // The configuration is invalid for current operation. + CodeMissingConfiguration = localCode{57, "Missing Configuration", nil} // The configuration is missing for current operation. + CodeNotImplemented = localCode{58, "Not Implemented", nil} // The operation is not implemented yet. + CodeNotSupported = localCode{59, "Not Supported", nil} // The operation is not supported yet. + CodeOperationFailed = localCode{60, "Operation Failed", nil} // I tried, but I cannot give you what you want. + CodeNotAuthorized = localCode{61, "Not Authorized", nil} // Not Authorized. + CodeSecurityReason = localCode{62, "Security Reason", nil} // Security Reason. + CodeServerBusy = localCode{63, "Server Is Busy", nil} // Server is busy, please try again later. + CodeUnknown = localCode{64, "Unknown Error", nil} // Unknown error. + CodeResourceNotExist = localCode{65, "Resource Not Exist", nil} // Resource does not exist. + CodeInvalidRequest = localCode{66, "Invalid Request", nil} // Invalid request. + CodeBusinessValidationFailed = localCode{300, "Business Validation Failed", nil} // Business validation failed. +) + +// New creates and returns an error code. +// Note that it returns an interface object of Code. +func New(code int, message string, detail interface{}) Code { + return localCode{ + code: code, + message: message, + detail: detail, + } +} + +// Code returns the integer number of current error code. +func (c localCode) Code() int { + return c.code +} + +// Message returns the brief message for current error code. +func (c localCode) Message() string { + return c.message +} + +// Detail returns the detailed information of current error code, +// which is mainly designed as an extension field for error code. +func (c localCode) Detail() interface{} { + return c.detail +} + +// String returns current error code as a string. +func (c localCode) String() string { + if c.detail != nil { + return fmt.Sprintf(`%d:%s %v`, c.code, c.message, c.detail) + } + if c.message != "" { + return fmt.Sprintf(`%d:%s`, c.code, c.message) + } + return fmt.Sprintf(`%d`, c.code) +} diff --git a/errors/gerror/gerror.go b/errors/gerror/gerror.go index 7e1e9af03..268af2fab 100644 --- a/errors/gerror/gerror.go +++ b/errors/gerror/gerror.go @@ -12,35 +12,36 @@ package gerror import ( "fmt" + "github.com/gogf/gf/errors/gcode" ) // apiCode is the interface for Code feature. type apiCode interface { - Error() string // It should be an error. - Code() int + Error() string + Code() gcode.Code } // apiStack is the interface for Stack feature. type apiStack interface { - Error() string // It should be an error. + Error() string Stack() string } // apiCause is the interface for Cause feature. type apiCause interface { - Error() string // It should be an error. + Error() string Cause() error } // apiCurrent is the interface for Current feature. type apiCurrent interface { - Error() string // It should be an error. + Error() string Current() error } // apiNext is the interface for Next feature. type apiNext interface { - Error() string // It should be an error. + Error() string Next() error } @@ -49,7 +50,7 @@ func New(text string) error { return &Error{ stack: callers(), text: text, - code: CodeNil, + code: gcode.CodeNil, } } @@ -58,7 +59,7 @@ func Newf(format string, args ...interface{}) error { return &Error{ stack: callers(), text: fmt.Sprintf(format, args...), - code: CodeNil, + code: gcode.CodeNil, } } @@ -68,7 +69,7 @@ func NewSkip(skip int, text string) error { return &Error{ stack: callers(skip), text: text, - code: CodeNil, + code: gcode.CodeNil, } } @@ -78,7 +79,7 @@ func NewSkipf(skip int, format string, args ...interface{}) error { return &Error{ stack: callers(skip), text: fmt.Sprintf(format, args...), - code: CodeNil, + code: gcode.CodeNil, } } @@ -142,7 +143,7 @@ func WrapSkipf(skip int, err error, format string, args ...interface{}) error { } // NewCode creates and returns an error that has error code and given text. -func NewCode(code int, text ...string) error { +func NewCode(code gcode.Code, text ...string) error { errText := "" if len(text) > 0 { errText = text[0] @@ -155,7 +156,7 @@ func NewCode(code int, text ...string) error { } // NewCodef returns an error that has error code and formats as the given format and args. -func NewCodef(code int, format string, args ...interface{}) error { +func NewCodef(code gcode.Code, format string, args ...interface{}) error { return &Error{ stack: callers(), text: fmt.Sprintf(format, args...), @@ -165,7 +166,7 @@ func NewCodef(code int, format string, args ...interface{}) error { // NewCodeSkip creates and returns an error which has error code and is formatted from given text. // The parameter <skip> specifies the stack callers skipped amount. -func NewCodeSkip(code, skip int, text ...string) error { +func NewCodeSkip(code gcode.Code, skip int, text ...string) error { errText := "" if len(text) > 0 { errText = text[0] @@ -179,7 +180,7 @@ func NewCodeSkip(code, skip int, text ...string) error { // NewCodeSkipf returns an error that has error code and formats as the given format and args. // The parameter <skip> specifies the stack callers skipped amount. -func NewCodeSkipf(code, skip int, format string, args ...interface{}) error { +func NewCodeSkipf(code gcode.Code, skip int, format string, args ...interface{}) error { return &Error{ stack: callers(skip), text: fmt.Sprintf(format, args...), @@ -189,7 +190,7 @@ func NewCodeSkipf(code, skip int, format string, args ...interface{}) error { // WrapCode wraps error with code and text. // It returns nil if given err is nil. -func WrapCode(code int, err error, text ...string) error { +func WrapCode(code gcode.Code, err error, text ...string) error { if err == nil { return nil } @@ -207,7 +208,7 @@ func WrapCode(code int, err error, text ...string) error { // WrapCodef wraps error with code and format specifier. // It returns nil if given <err> is nil. -func WrapCodef(code int, err error, format string, args ...interface{}) error { +func WrapCodef(code gcode.Code, err error, format string, args ...interface{}) error { if err == nil { return nil } @@ -222,7 +223,7 @@ func WrapCodef(code int, err error, format string, args ...interface{}) error { // WrapCodeSkip wraps error with code and text. // It returns nil if given err is nil. // The parameter <skip> specifies the stack callers skipped amount. -func WrapCodeSkip(code, skip int, err error, text ...string) error { +func WrapCodeSkip(code gcode.Code, skip int, err error, text ...string) error { if err == nil { return nil } @@ -241,7 +242,7 @@ func WrapCodeSkip(code, skip int, err error, text ...string) error { // WrapCodeSkipf wraps error with code and text that is formatted with given format and args. // It returns nil if given err is nil. // The parameter <skip> specifies the stack callers skipped amount. -func WrapCodeSkipf(code, skip int, err error, format string, args ...interface{}) error { +func WrapCodeSkipf(code gcode.Code, skip int, err error, format string, args ...interface{}) error { if err == nil { return nil } @@ -255,23 +256,13 @@ func WrapCodeSkipf(code, skip int, err error, format string, args ...interface{} // Code returns the error code of current error. // It returns CodeNil if it has no error code or it does not implements interface Code. -func Code(err error) int { +func Code(err error) gcode.Code { if err != nil { if e, ok := err.(apiCode); ok { return e.Code() } } - return CodeNil -} - -// CodeMessage retrieves and returns the error code message from given error. -func CodeMessage(err error) string { - return Message(Code(err)) -} - -// Message returns the message string for specified code. -func Message(code int) string { - return codeMessageMap[code] + return gcode.CodeNil } // Cause returns the root cause error of <err>. diff --git a/errors/gerror/gerror_code.go b/errors/gerror/gerror_code.go deleted file mode 100644 index 699deaa11..000000000 --- a/errors/gerror/gerror_code.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gerror - -// Reserved internal error code of framework: code < 1000. - -const ( - CodeNil = -1 // No error code specified. - CodeOk = 0 // It is OK. - CodeInternalError = 50 // An error occurred internally. - CodeValidationFailed = 51 // Data validation failed. - CodeDbOperationError = 52 // Database operation error. - CodeInvalidParameter = 53 // The given parameter for current operation is invalid. - CodeMissingParameter = 54 // Parameter for current operation is missing. - CodeInvalidOperation = 55 // The function cannot be used like this. - CodeInvalidConfiguration = 56 // The configuration is invalid for current operation. - CodeMissingConfiguration = 57 // The configuration is missing for current operation. - CodeNotImplemented = 58 // The operation is not implemented yet. - CodeNotSupported = 59 // The operation is not supported yet. - CodeOperationFailed = 60 // I tried, but I cannot give you what you want. - CodeNotAuthorized = 61 // Not Authorized. - CodeSecurityReason = 62 // Security Reason. - CodeServerBusy = 63 // Server is busy, please try again later. - CodeUnknown = 64 // Unknown error. - CodeResourceNotExist = 65 // Resource does not exist. - CodeInvalidRequest = 66 // Invalid request. - CodeBusinessValidationFailed = 300 // Business validation failed. -) - -var ( - // codeMessageMap is the mapping from code to according string message. - codeMessageMap = map[int]string{ - CodeNil: "", - CodeOk: "OK", - CodeInternalError: "Internal Error", - CodeValidationFailed: "Validation Failed", - CodeDbOperationError: "Database Operation Error", - CodeInvalidParameter: "Invalid Parameter", - CodeMissingParameter: "Missing Parameter", - CodeInvalidOperation: "Invalid Operation", - CodeInvalidConfiguration: "Invalid Configuration", - CodeMissingConfiguration: "Missing Configuration", - CodeNotImplemented: "Not Implemented", - CodeNotSupported: "Not Supported", - CodeOperationFailed: "Operation Failed", - CodeNotAuthorized: "Not Authorized", - CodeSecurityReason: "Security Reason", - CodeServerBusy: "Server Is Busy", - CodeUnknown: "Unknown Error", - CodeResourceNotExist: "Resource Not Exist", - CodeInvalidRequest: "Invalid Request", - CodeBusinessValidationFailed: "Business Validation Failed", - } -) - -// RegisterCode registers custom error code to global error codes for gerror recognition. -func RegisterCode(code int, message string) { - codeMessageMap[code] = message -} - -// RegisterCodeMap registers custom error codes to global error codes for gerror recognition using map. -func RegisterCodeMap(codes map[int]string) { - for k, v := range codes { - codeMessageMap[k] = v - } -} diff --git a/errors/gerror/gerror_error.go b/errors/gerror/gerror_error.go index 97e22f0cd..bbc00bdf1 100644 --- a/errors/gerror/gerror_error.go +++ b/errors/gerror/gerror_error.go @@ -10,6 +10,7 @@ import ( "bytes" "errors" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/internal/utils" "io" "runtime" @@ -18,10 +19,10 @@ import ( // Error is custom error for additional features. type Error struct { - error error // Wrapped error. - stack stack // Stack array, which records the stack information when this error is created or wrapped. - text string // Error text, which is created by New* functions. - code int // Error code if necessary. + error error // Wrapped error. + stack stack // Stack array, which records the stack information when this error is created or wrapped. + text string // Error text, which is created by New* functions. + code gcode.Code // Error code if necessary. } const ( @@ -47,8 +48,8 @@ func (err *Error) Error() string { return "" } errStr := err.text - if errStr == "" { - errStr = Message(err.code) + if errStr == "" && err.code != nil { + errStr = err.code.Message() } if err.error != nil { if errStr != "" { @@ -61,9 +62,9 @@ func (err *Error) Error() string { // Code returns the error code. // It returns CodeNil if it has no error code. -func (err *Error) Code() int { +func (err *Error) Code() gcode.Code { if err == nil { - return CodeNil + return gcode.CodeNil } return err.code } diff --git a/errors/gerror/gerror_option.go b/errors/gerror/gerror_option.go index c7c33aa18..30c2c38e5 100644 --- a/errors/gerror/gerror_option.go +++ b/errors/gerror/gerror_option.go @@ -6,12 +6,14 @@ package gerror +import "github.com/gogf/gf/errors/gcode" + // Option is option for creating error. type Option struct { - Error error // Wrapped error if any. - Stack bool // Whether recording stack information into error. - Text string // Error text, which is created by New* functions. - Code int // Error code if necessary. + Error error // Wrapped error if any. + Stack bool // Whether recording stack information into error. + Text string // Error text, which is created by New* functions. + Code gcode.Code // Error code if necessary. } // NewOption creates and returns an error with Option. diff --git a/errors/gerror/gerror_z_bench_test.go b/errors/gerror/gerror_z_bench_test.go index fea2aaf8f..7e510abdb 100644 --- a/errors/gerror/gerror_z_bench_test.go +++ b/errors/gerror/gerror_z_bench_test.go @@ -8,6 +8,7 @@ package gerror_test import ( "errors" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "testing" ) @@ -55,36 +56,36 @@ func Benchmark_NewSkipf(b *testing.B) { func Benchmark_NewCode(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.NewCode(500, "test") + gerror.NewCode(gcode.New(500, "", nil), "test") } } func Benchmark_NewCodef(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.NewCodef(500, "%s", "test") + gerror.NewCodef(gcode.New(500, "", nil), "%s", "test") } } func Benchmark_NewCodeSkip(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.NewCodeSkip(1, 500, "test") + gerror.NewCodeSkip(gcode.New(1, "", nil), 500, "test") } } func Benchmark_NewCodeSkipf(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.NewCodeSkipf(1, 500, "%s", "test") + gerror.NewCodeSkipf(gcode.New(1, "", nil), 500, "%s", "test") } } func Benchmark_WrapCode(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.WrapCode(500, baseError, "test") + gerror.WrapCode(gcode.New(500, "", nil), baseError, "test") } } func Benchmark_WrapCodef(b *testing.B) { for i := 0; i < b.N; i++ { - gerror.WrapCodef(500, baseError, "test") + gerror.WrapCodef(gcode.New(500, "", nil), baseError, "test") } } diff --git a/errors/gerror/gerror_z_example_test.go b/errors/gerror/gerror_z_example_test.go index 7c627dbbe..f52528854 100644 --- a/errors/gerror/gerror_z_example_test.go +++ b/errors/gerror/gerror_z_example_test.go @@ -9,11 +9,12 @@ package gerror_test import ( "errors" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" ) func ExampleNewCode() { - err := gerror.NewCode(10000, "My Error") + err := gerror.NewCode(gcode.New(10000, "", nil), "My Error") fmt.Println(err.Error()) fmt.Println(gerror.Code(err)) @@ -23,9 +24,9 @@ func ExampleNewCode() { } func ExampleNewCodef() { - err := gerror.NewCodef(10000, "It's %s", "My Error") + err := gerror.NewCodef(gcode.New(10000, "", nil), "It's %s", "My Error") fmt.Println(err.Error()) - fmt.Println(gerror.Code(err)) + fmt.Println(gerror.Code(err).Code()) // Output: // It's My Error @@ -34,9 +35,9 @@ func ExampleNewCodef() { func ExampleWrapCode() { err1 := errors.New("permission denied") - err2 := gerror.WrapCode(10000, err1, "Custom Error") + err2 := gerror.WrapCode(gcode.New(10000, "", nil), err1, "Custom Error") fmt.Println(err2.Error()) - fmt.Println(gerror.Code(err2)) + fmt.Println(gerror.Code(err2).Code()) // Output: // Custom Error: permission denied @@ -45,9 +46,9 @@ func ExampleWrapCode() { func ExampleWrapCodef() { err1 := errors.New("permission denied") - err2 := gerror.WrapCodef(10000, err1, "It's %s", "Custom Error") + err2 := gerror.WrapCodef(gcode.New(10000, "", nil), err1, "It's %s", "Custom Error") fmt.Println(err2.Error()) - fmt.Println(gerror.Code(err2)) + fmt.Println(gerror.Code(err2).Code()) // Output: // It's Custom Error: permission denied diff --git a/errors/gerror/gerror_z_unit_test.go b/errors/gerror/gerror_z_unit_test.go index 0bffed596..05521833c 100644 --- a/errors/gerror/gerror_z_unit_test.go +++ b/errors/gerror/gerror_z_unit_test.go @@ -9,6 +9,7 @@ package gerror_test import ( "errors" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/internal/json" "testing" @@ -261,51 +262,51 @@ func Test_Code(t *testing.T) { t.Assert(err.Error(), "123") }) gtest.C(t, func(t *gtest.T) { - err := gerror.NewCode(gerror.CodeUnknown, "123") - t.Assert(gerror.Code(err), gerror.CodeUnknown) + err := gerror.NewCode(gcode.CodeUnknown, "123") + t.Assert(gerror.Code(err), gcode.CodeUnknown) t.Assert(err.Error(), "123") }) gtest.C(t, func(t *gtest.T) { - err := gerror.NewCodef(1, "%s", "123") - t.Assert(gerror.Code(err), 1) + err := gerror.NewCodef(gcode.New(1, "", nil), "%s", "123") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "123") }) gtest.C(t, func(t *gtest.T) { - err := gerror.NewCodeSkip(1, 0, "123") - t.Assert(gerror.Code(err), 1) + err := gerror.NewCodeSkip(gcode.New(1, "", nil), 0, "123") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "123") }) gtest.C(t, func(t *gtest.T) { - err := gerror.NewCodeSkipf(1, 0, "%s", "123") - t.Assert(gerror.Code(err), 1) + err := gerror.NewCodeSkipf(gcode.New(1, "", nil), 0, "%s", "123") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "123") }) gtest.C(t, func(t *gtest.T) { err := errors.New("1") err = gerror.Wrap(err, "2") - err = gerror.WrapCode(1, err, "3") - t.Assert(gerror.Code(err), 1) + err = gerror.WrapCode(gcode.New(1, "", nil), err, "3") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "3: 2: 1") }) gtest.C(t, func(t *gtest.T) { err := errors.New("1") err = gerror.Wrap(err, "2") - err = gerror.WrapCodef(1, err, "%s", "3") - t.Assert(gerror.Code(err), 1) + err = gerror.WrapCodef(gcode.New(1, "", nil), err, "%s", "3") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "3: 2: 1") }) gtest.C(t, func(t *gtest.T) { err := errors.New("1") err = gerror.Wrap(err, "2") - err = gerror.WrapCodeSkip(1, 100, err, "3") - t.Assert(gerror.Code(err), 1) + err = gerror.WrapCodeSkip(gcode.New(1, "", nil), 100, err, "3") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "3: 2: 1") }) gtest.C(t, func(t *gtest.T) { err := errors.New("1") err = gerror.Wrap(err, "2") - err = gerror.WrapCodeSkipf(1, 100, err, "%s", "3") - t.Assert(gerror.Code(err), 1) + err = gerror.WrapCodeSkipf(gcode.New(1, "", nil), 100, err, "%s", "3") + t.Assert(gerror.Code(err).Code(), 1) t.Assert(err.Error(), "3: 2: 1") }) } @@ -318,36 +319,3 @@ func Test_Json(t *testing.T) { t.Assert(string(b), `"2: 1"`) }) } - -func Test_Message(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - t.Assert(gerror.Message(-100), ``) - t.Assert(gerror.Message(gerror.CodeNil), ``) - t.Assert(gerror.Message(gerror.CodeOk), `OK`) - }) -} - -func Test_CodeMessage(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - err := gerror.NewCode(gerror.CodeUnknown) - t.Assert(gerror.CodeMessage(err), `Unknown Error`) - }) -} - -func Test_RegisterCode(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - gerror.RegisterCode(10086, "MobileTelecom") - t.Assert(gerror.Message(10086), `MobileTelecom`) - }) -} - -func Test_RegisterCodeMap(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - gerror.RegisterCodeMap(map[int]string{ - 10087: "MobileTelecom 10087", - 10088: "MobileTelecom 10088", - }) - t.Assert(gerror.Message(10087), `MobileTelecom 10087`) - t.Assert(gerror.Message(10088), `MobileTelecom 10088`) - }) -} diff --git a/frame/gins/gins_database.go b/frame/gins/gins_database.go index dc49a18a6..e27f7ce73 100644 --- a/frame/gins/gins_database.go +++ b/frame/gins/gins_database.go @@ -9,6 +9,7 @@ package gins import ( "context" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/text/gstr" @@ -54,7 +55,7 @@ func Database(name ...string) gdb.DB { exampleFileName := "config.example.toml" if exampleConfigFilePath, _ := Config().GetFilePath(exampleFileName); exampleConfigFilePath != "" { panic(gerror.WrapCodef( - gerror.CodeMissingConfiguration, + gcode.CodeMissingConfiguration, err, `configuration file "%s" not found, but found "%s", did you miss renaming the example configuration file?`, Config().GetFileName(), @@ -62,7 +63,7 @@ func Database(name ...string) gdb.DB { )) } else { panic(gerror.WrapCodef( - gerror.CodeMissingConfiguration, + gcode.CodeMissingConfiguration, err, `configuration file "%s" not found, did you miss the configuration file or the misspell the configuration file name?`, Config().GetFileName(), @@ -70,7 +71,7 @@ func Database(name ...string) gdb.DB { } } panic(gerror.WrapCodef( - gerror.CodeMissingConfiguration, + gcode.CodeMissingConfiguration, err, `database initialization failed: "%s" node not found, is configuration file or configuration node missing?`, configNodeNameDatabase, diff --git a/i18n/gi18n/gi18n_manager.go b/i18n/gi18n/gi18n_manager.go index 90ca866d7..e5d18f7bc 100644 --- a/i18n/gi18n/gi18n_manager.go +++ b/i18n/gi18n/gi18n_manager.go @@ -9,6 +9,7 @@ package gi18n import ( "context" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "strings" @@ -101,7 +102,7 @@ func (m *Manager) SetPath(path string) error { } else { realPath, _ := gfile.Search(path) if realPath == "" { - return gerror.NewCodef(gerror.CodeInvalidParameter, `%s does not exist`, path) + return gerror.NewCodef(gcode.CodeInvalidParameter, `%s does not exist`, path) } m.options.Path = realPath } diff --git a/net/ghttp/ghttp_func.go b/net/ghttp/ghttp_func.go index 2c569c0ac..a4d96037e 100644 --- a/net/ghttp/ghttp_func.go +++ b/net/ghttp/ghttp_func.go @@ -7,6 +7,7 @@ package ghttp import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/net/ghttp/internal/httputil" ) @@ -36,13 +37,13 @@ func niceCallFunc(f func()) { // Note that there's a skip pointing the start stacktrace // of the real error point. if err, ok := exception.(error); ok { - if gerror.Code(err) != gerror.CodeNil { + if gerror.Code(err) != gcode.CodeNil { panic(err) } else { - panic(gerror.WrapCodeSkip(gerror.CodeInternalError, 1, err, "")) + panic(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, err, "")) } } else { - panic(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%+v", exception)) + panic(gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%+v", exception)) } } } diff --git a/net/ghttp/ghttp_middleware_handler_response.go b/net/ghttp/ghttp_middleware_handler_response.go index f8c71c318..e37e92374 100644 --- a/net/ghttp/ghttp_middleware_handler_response.go +++ b/net/ghttp/ghttp_middleware_handler_response.go @@ -7,6 +7,7 @@ package ghttp import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" ) @@ -28,11 +29,11 @@ func MiddlewareHandlerResponse(r *Request) { res, err = r.GetHandlerResponse() if err != nil { code := gerror.Code(err) - if code == gerror.CodeNil { - code = gerror.CodeInternalError + if code == gcode.CodeNil { + code = gcode.CodeInternalError } internalErr = r.Response.WriteJson(DefaultHandlerResponse{ - Code: code, + Code: code.Code(), Message: err.Error(), Data: nil, }) @@ -42,7 +43,7 @@ func MiddlewareHandlerResponse(r *Request) { return } internalErr = r.Response.WriteJson(DefaultHandlerResponse{ - Code: gerror.CodeOk, + Code: gcode.CodeOK.Code(), Message: "", Data: res, }) diff --git a/net/ghttp/ghttp_request_middleware.go b/net/ghttp/ghttp_request_middleware.go index 66dc66275..7f7956a37 100644 --- a/net/ghttp/ghttp_request_middleware.go +++ b/net/ghttp/ghttp_request_middleware.go @@ -7,6 +7,7 @@ package ghttp import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "net/http" "reflect" @@ -105,7 +106,7 @@ func (m *middleware) Next() { // Create a new error with stack info. // Note that there's a skip pointing the start stacktrace // of the real error point. - m.request.error = gerror.WrapCodeSkip(gerror.CodeInternalError, 1, exception, "") + m.request.error = gerror.WrapCodeSkip(gcode.CodeInternalError, 1, exception, "") } m.request.Response.WriteStatus(http.StatusInternalServerError, exception) loop = false diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index e0381e854..8c9689b2e 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -13,6 +13,7 @@ import ( "github.com/gogf/gf/encoding/gjson" "github.com/gogf/gf/encoding/gurl" "github.com/gogf/gf/encoding/gxml" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "github.com/gogf/gf/internal/utils" @@ -300,7 +301,7 @@ func (r *Request) parseQuery() { var err error r.queryMap, err = gstr.Parse(r.URL.RawQuery) if err != nil { - panic(gerror.WrapCode(gerror.CodeInvalidParameter, err, "")) + panic(gerror.WrapCode(gcode.CodeInvalidParameter, err, "")) } } } @@ -355,12 +356,12 @@ func (r *Request) parseForm() { if gstr.Contains(contentType, "multipart/") { // multipart/form-data, multipart/mixed if err = r.ParseMultipartForm(r.Server.config.FormParsingMemory); err != nil { - panic(gerror.WrapCode(gerror.CodeInvalidRequest, err, "")) + panic(gerror.WrapCode(gcode.CodeInvalidRequest, err, "")) } } else if gstr.Contains(contentType, "form") { // application/x-www-form-urlencoded if err = r.Request.ParseForm(); err != nil { - panic(gerror.WrapCode(gerror.CodeInvalidRequest, err, "")) + panic(gerror.WrapCode(gcode.CodeInvalidRequest, err, "")) } } if len(r.PostForm) > 0 { @@ -403,7 +404,7 @@ func (r *Request) parseForm() { } if params != "" { if r.formMap, err = gstr.Parse(params); err != nil { - panic(gerror.WrapCode(gerror.CodeInvalidParameter, err, "")) + panic(gerror.WrapCode(gcode.CodeInvalidParameter, err, "")) } } } diff --git a/net/ghttp/ghttp_request_param_file.go b/net/ghttp/ghttp_request_param_file.go index aea6961cf..7219117e2 100644 --- a/net/ghttp/ghttp_request_param_file.go +++ b/net/ghttp/ghttp_request_param_file.go @@ -8,6 +8,7 @@ package ghttp import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/os/gfile" @@ -36,7 +37,7 @@ type UploadFiles []*UploadFile func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename string, err error) { if f == nil { return "", gerror.NewCode( - gerror.CodeMissingParameter, + gcode.CodeMissingParameter, "file is empty, maybe you retrieve it from invalid field name or form enctype", ) } @@ -45,7 +46,7 @@ func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename stri return } } else if !gfile.IsDir(dirPath) { - return "", gerror.NewCode(gerror.CodeInvalidParameter, `parameter "dirPath" should be a directory path`) + return "", gerror.NewCode(gcode.CodeInvalidParameter, `parameter "dirPath" should be a directory path`) } file, err := f.Open() @@ -80,7 +81,7 @@ func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename stri func (fs UploadFiles) Save(dirPath string, randomlyRename ...bool) (filenames []string, err error) { if len(fs) == 0 { return nil, gerror.NewCode( - gerror.CodeMissingParameter, + gcode.CodeMissingParameter, "file array is empty, maybe you retrieve it from invalid field name or form enctype", ) } diff --git a/net/ghttp/ghttp_server.go b/net/ghttp/ghttp_server.go index a0153aa0c..1b2eef058 100644 --- a/net/ghttp/ghttp_server.go +++ b/net/ghttp/ghttp_server.go @@ -10,6 +10,7 @@ import ( "bytes" "context" "github.com/gogf/gf/debug/gdebug" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "net/http" @@ -107,7 +108,7 @@ func GetServer(name ...interface{}) *Server { } // Initialize the server using default configurations. if err := s.SetConfig(NewConfig()); err != nil { - panic(gerror.WrapCode(gerror.CodeInvalidConfiguration, err, "")) + panic(gerror.WrapCode(gcode.CodeInvalidConfiguration, err, "")) } // Record the server to internal server mapping by name. serverMapping.Set(serverName, s) @@ -125,7 +126,7 @@ func (s *Server) Start() error { // Server can only be run once. if s.Status() == ServerStatusRunning { - return gerror.NewCode(gerror.CodeInvalidOperation, "server is already running") + return gerror.NewCode(gcode.CodeInvalidOperation, "server is already running") } // Logging path setting check. @@ -141,7 +142,7 @@ func (s *Server) Start() error { path = gfile.Join(s.config.SessionPath, s.name) if !gfile.Exists(path) { if err := gfile.Mkdir(path); err != nil { - return gerror.WrapCodef(gerror.CodeInternalError, err, `mkdir failed for "%s"`, path) + return gerror.WrapCodef(gcode.CodeInternalError, err, `mkdir failed for "%s"`, path) } } } @@ -176,7 +177,7 @@ func (s *Server) Start() error { // it then returns an error of invalid usage of server. if len(s.routesMap) == 0 && !s.config.FileServerEnabled { return gerror.NewCode( - gerror.CodeInvalidOperation, + gcode.CodeInvalidOperation, `there's no route set or static feature enabled, did you forget import the router?`, ) } diff --git a/net/ghttp/ghttp_server_admin_process.go b/net/ghttp/ghttp_server_admin_process.go index 9fe65b8d3..3f854dcbb 100644 --- a/net/ghttp/ghttp_server_admin_process.go +++ b/net/ghttp/ghttp_server_admin_process.go @@ -10,6 +10,7 @@ import ( "bytes" "context" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/text/gstr" @@ -52,7 +53,7 @@ var serverProcessStatus = gtype.NewInt() // The optional parameter <newExeFilePath> specifies the new binary file for creating process. func RestartAllServer(newExeFilePath ...string) error { if !gracefulEnabled { - return gerror.NewCode(gerror.CodeInvalidOperation, "graceful reload feature is disabled") + return gerror.NewCode(gcode.CodeInvalidOperation, "graceful reload feature is disabled") } serverActionLocker.Lock() defer serverActionLocker.Unlock() @@ -85,10 +86,10 @@ func checkProcessStatus() error { if status > 0 { switch status { case adminActionRestarting: - return gerror.NewCode(gerror.CodeInvalidOperation, "server is restarting") + return gerror.NewCode(gcode.CodeInvalidOperation, "server is restarting") case adminActionShuttingDown: - return gerror.NewCode(gerror.CodeInvalidOperation, "server is shutting down") + return gerror.NewCode(gcode.CodeInvalidOperation, "server is shutting down") } } return nil @@ -100,7 +101,7 @@ func checkActionFrequency() error { interval := gtime.TimestampMilli() - serverActionLastTime.Val() if interval < adminActionIntervalLimit { return gerror.NewCodef( - gerror.CodeInvalidOperation, + gcode.CodeInvalidOperation, "too frequent action, please retry in %d ms", adminActionIntervalLimit-interval, ) diff --git a/net/ghttp/ghttp_server_graceful.go b/net/ghttp/ghttp_server_graceful.go index 6af3a3368..8f6d60b53 100644 --- a/net/ghttp/ghttp_server_graceful.go +++ b/net/ghttp/ghttp_server_graceful.go @@ -10,6 +10,7 @@ import ( "context" "crypto/tls" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gproc" "github.com/gogf/gf/os/gres" @@ -122,7 +123,7 @@ func (s *gracefulServer) ListenAndServeTLS(certFile, keyFile string, tlsConfig . } if err != nil { - return gerror.WrapCodef(gerror.CodeInternalError, err, `open cert file "%s","%s" failed`, certFile, keyFile) + return gerror.WrapCodef(gcode.CodeInternalError, err, `open cert file "%s","%s" failed`, certFile, keyFile) } ln, err := s.getNetListener() if err != nil { diff --git a/net/ghttp/ghttp_server_handler.go b/net/ghttp/ghttp_server_handler.go index 7803a295d..30d747c80 100644 --- a/net/ghttp/ghttp_server_handler.go +++ b/net/ghttp/ghttp_server_handler.go @@ -7,6 +7,7 @@ package ghttp import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/internal/intlog" "net/http" "os" @@ -67,13 +68,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if exception := recover(); exception != nil { request.Response.WriteStatus(http.StatusInternalServerError) if err, ok := exception.(error); ok { - if code := gerror.Code(err); code != gerror.CodeNil { + if code := gerror.Code(err); code != gcode.CodeNil { s.handleErrorLog(err, request) } else { - s.handleErrorLog(gerror.WrapCodeSkip(gerror.CodeInternalError, 1, err, ""), request) + s.handleErrorLog(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, err, ""), request) } } else { - s.handleErrorLog(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%+v", exception), request) + s.handleErrorLog(gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%+v", exception), request) } } } diff --git a/net/ghttp/ghttp_server_router.go b/net/ghttp/ghttp_server_router.go index 1dd4b630b..83d061b5e 100644 --- a/net/ghttp/ghttp_server_router.go +++ b/net/ghttp/ghttp_server_router.go @@ -9,6 +9,7 @@ package ghttp import ( "fmt" "github.com/gogf/gf/container/gtype" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "strings" @@ -53,7 +54,7 @@ func (s *Server) parsePattern(pattern string) (domain, method, path string, err } } if path == "" { - err = gerror.NewCode(gerror.CodeInvalidParameter, "invalid pattern: URI should not be empty") + err = gerror.NewCode(gcode.CodeInvalidParameter, "invalid pattern: URI should not be empty") } if path != "/" { path = strings.TrimRight(path, "/") diff --git a/net/ghttp/ghttp_server_router_serve.go b/net/ghttp/ghttp_server_router_serve.go index d3614312e..00987de67 100644 --- a/net/ghttp/ghttp_server_router_serve.go +++ b/net/ghttp/ghttp_server_router_serve.go @@ -8,6 +8,7 @@ package ghttp import ( "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "strings" @@ -191,7 +192,7 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han parsedItemList.PushBack(parsedItem) default: - panic(gerror.NewCodef(gerror.CodeInternalError, `invalid handler type %d`, item.Type)) + panic(gerror.NewCodef(gcode.CodeInternalError, `invalid handler type %d`, item.Type)) } } } diff --git a/net/ghttp/ghttp_server_service_handler.go b/net/ghttp/ghttp_server_service_handler.go index 1b846e7e1..5fc5ca6ab 100644 --- a/net/ghttp/ghttp_server_service_handler.go +++ b/net/ghttp/ghttp_server_service_handler.go @@ -9,6 +9,7 @@ package ghttp import ( "bytes" "github.com/gogf/gf/debug/gdebug" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "reflect" "strings" @@ -129,13 +130,13 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN if reflectType.NumIn() == 0 || reflectType.NumIn() > 2 || reflectType.NumOut() > 2 { if pkgPath != "" { err = gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid handler: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" or "func(context.Context)/func(context.Context,Request)/func(context.Context,Request) error/func(context.Context,Request)(Response,error)" is required`, pkgPath, objName, methodName, reflect.TypeOf(f).String(), ) } else { err = gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid handler: defined as "%s", but "func(*ghttp.Request)" or "func(context.Context)/func(context.Context,Request)/func(context.Context,Request) error/func(context.Context,Request)(Response,error)" is required`, reflect.TypeOf(f).String(), ) @@ -145,7 +146,7 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN if reflectType.In(0).String() != "context.Context" { err = gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid handler: defined as "%s", but the first input parameter should be type of "context.Context"`, reflect.TypeOf(f).String(), ) @@ -154,7 +155,7 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN if reflectType.NumOut() > 0 && reflectType.Out(reflectType.NumOut()-1).String() != "error" { err = gerror.NewCodef( - gerror.CodeInvalidParameter, + gcode.CodeInvalidParameter, `invalid handler: defined as "%s", but the last output parameter should be type of "error"`, reflect.TypeOf(f).String(), ) diff --git a/net/ghttp/internal/client/client.go b/net/ghttp/internal/client/client.go index 2f635af85..c4f649e2f 100644 --- a/net/ghttp/internal/client/client.go +++ b/net/ghttp/internal/client/client.go @@ -12,6 +12,7 @@ import ( "crypto/tls" "fmt" "github.com/gogf/gf" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gfile" "github.com/gogf/gf/text/gstr" @@ -246,14 +247,14 @@ func (c *Client) SetProxy(proxyURL string) { func (c *Client) SetTLSKeyCrt(crtFile, keyFile string) error { tlsConfig, err := LoadKeyCrt(crtFile, keyFile) if err != nil { - return gerror.WrapCode(gerror.CodeInternalError, err, "LoadKeyCrt failed") + return gerror.WrapCode(gcode.CodeInternalError, err, "LoadKeyCrt failed") } if v, ok := c.Transport.(*http.Transport); ok { tlsConfig.InsecureSkipVerify = true v.TLSClientConfig = tlsConfig return nil } - return gerror.NewCode(gerror.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`) + return gerror.NewCode(gcode.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`) } // SetTLSConfig sets the TLS configuration of client. @@ -262,7 +263,7 @@ func (c *Client) SetTLSConfig(tlsConfig *tls.Config) error { v.TLSClientConfig = tlsConfig return nil } - return gerror.NewCode(gerror.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`) + return gerror.NewCode(gcode.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`) } // LoadKeyCrt creates and returns a TLS configuration object with given certificate and key files. diff --git a/net/ghttp/internal/client/client_request.go b/net/ghttp/internal/client/client_request.go index 781c5a2ff..3f7b2b85d 100644 --- a/net/ghttp/internal/client/client_request.go +++ b/net/ghttp/internal/client/client_request.go @@ -9,6 +9,7 @@ package client import ( "bytes" "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/internal/json" @@ -188,7 +189,7 @@ func (c *Client) prepareRequest(method, url string, data ...interface{}) (req *h if len(array[1]) > 6 && strings.Compare(array[1][0:6], "@file:") == 0 { path := array[1][6:] if !gfile.Exists(path) { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `"%s" does not exist`, path) } if file, err := writer.CreateFormFile(array[0], gfile.Basename(path)); err == nil { if f, err := os.Open(path); err == nil { diff --git a/net/gipv4/gipv4_ip.go b/net/gipv4/gipv4_ip.go index aab88ccea..e1819e078 100644 --- a/net/gipv4/gipv4_ip.go +++ b/net/gipv4/gipv4_ip.go @@ -8,6 +8,7 @@ package gipv4 import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "net" "strconv" @@ -38,7 +39,7 @@ func GetIntranetIp() (ip string, err error) { return "", err } if len(ips) == 0 { - return "", gerror.NewCode(gerror.CodeOperationFailed, "no intranet ip found") + return "", gerror.NewCode(gcode.CodeOperationFailed, "no intranet ip found") } return ips[0], nil } diff --git a/net/gtcp/gtcp_server.go b/net/gtcp/gtcp_server.go index 57f21e62c..538dd6b2f 100644 --- a/net/gtcp/gtcp_server.go +++ b/net/gtcp/gtcp_server.go @@ -8,6 +8,7 @@ package gtcp import ( "crypto/tls" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "net" "sync" @@ -116,7 +117,7 @@ func (s *Server) Close() error { // Run starts running the TCP Server. func (s *Server) Run() (err error) { if s.handler == nil { - err = gerror.NewCode(gerror.CodeMissingConfiguration, "start running failed: socket handler not defined") + err = gerror.NewCode(gcode.CodeMissingConfiguration, "start running failed: socket handler not defined") glog.Error(err) return } diff --git a/net/gudp/gudp_server.go b/net/gudp/gudp_server.go index 64d5180c1..8e9bb8846 100644 --- a/net/gudp/gudp_server.go +++ b/net/gudp/gudp_server.go @@ -7,6 +7,7 @@ package gudp import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "net" @@ -78,7 +79,7 @@ func (s *Server) Close() error { // Run starts listening UDP connection. func (s *Server) Run() error { if s.handler == nil { - err := gerror.NewCode(gerror.CodeMissingConfiguration, "start running failed: socket handler not defined") + err := gerror.NewCode(gcode.CodeMissingConfiguration, "start running failed: socket handler not defined") glog.Error(err) return err } diff --git a/os/gcfg/gcfg_config.go b/os/gcfg/gcfg_config.go index bff1d6e04..f7db8f603 100644 --- a/os/gcfg/gcfg_config.go +++ b/os/gcfg/gcfg_config.go @@ -13,6 +13,7 @@ import ( "github.com/gogf/gf/container/garray" "github.com/gogf/gf/container/gmap" "github.com/gogf/gf/encoding/gjson" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/os/gcmd" @@ -142,7 +143,7 @@ func (c *Config) SetPath(path string) error { } else { buffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" does not exist`, path)) } - err := gerror.NewCode(gerror.CodeOperationFailed, buffer.String()) + err := gerror.NewCode(gcode.CodeOperationFailed, buffer.String()) if errorPrint() { glog.Error(err) } @@ -219,14 +220,14 @@ func (c *Config) AddPath(path string) error { } else { buffer.WriteString(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" does not exist`, path)) } - err := gerror.NewCode(gerror.CodeOperationFailed, buffer.String()) + err := gerror.NewCode(gcode.CodeOperationFailed, buffer.String()) if errorPrint() { glog.Error(err) } return err } if !isDir { - err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gcfg] AddPath failed: path "%s" should be directory type`, path) + err := gerror.NewCodef(gcode.CodeInvalidParameter, `[gcfg] AddPath failed: path "%s" should be directory type`, path) if errorPrint() { glog.Error(err) } @@ -329,7 +330,7 @@ func (c *Config) GetFilePath(file ...string) (path string, err error) { } else { buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" with no path configured", name)) } - err = gerror.NewCode(gerror.CodeOperationFailed, buffer.String()) + err = gerror.NewCode(gcode.CodeOperationFailed, buffer.String()) } return } diff --git a/os/gcfg/gcfg_config_api.go b/os/gcfg/gcfg_config_api.go index 4e7a2a9e8..f3adb7c9c 100644 --- a/os/gcfg/gcfg_config_api.go +++ b/os/gcfg/gcfg_config_api.go @@ -7,6 +7,7 @@ package gcfg import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "time" @@ -295,7 +296,7 @@ func (c *Config) GetStruct(pattern string, pointer interface{}, mapping ...map[s if j := c.getJson(); j != nil { return j.GetStruct(pattern, pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // GetStructs converts any slice to given struct slice. @@ -303,7 +304,7 @@ func (c *Config) GetStructs(pattern string, pointer interface{}, mapping ...map[ if j := c.getJson(); j != nil { return j.GetStructs(pattern, pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // GetMapToMap retrieves the value by specified `pattern` and converts it to specified map variable. @@ -312,7 +313,7 @@ func (c *Config) GetMapToMap(pattern string, pointer interface{}, mapping ...map if j := c.getJson(); j != nil { return j.GetMapToMap(pattern, pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // GetMapToMaps retrieves the value by specified `pattern` and converts it to specified map slice @@ -322,7 +323,7 @@ func (c *Config) GetMapToMaps(pattern string, pointer interface{}, mapping ...ma if j := c.getJson(); j != nil { return j.GetMapToMaps(pattern, pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // GetMapToMapsDeep retrieves the value by specified `pattern` and converts it to specified map slice @@ -332,7 +333,7 @@ func (c *Config) GetMapToMapsDeep(pattern string, pointer interface{}, mapping . if j := c.getJson(); j != nil { return j.GetMapToMapsDeep(pattern, pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // Map converts current Json object to map[string]interface{}. It returns nil if fails. @@ -358,7 +359,7 @@ func (c *Config) Struct(pointer interface{}, mapping ...map[string]string) error if j := c.getJson(); j != nil { return j.Struct(pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // Structs converts current Json object to specified object slice. @@ -367,7 +368,7 @@ func (c *Config) Structs(pointer interface{}, mapping ...map[string]string) erro if j := c.getJson(); j != nil { return j.Structs(pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // MapToMap converts current Json object to specified map variable. @@ -376,7 +377,7 @@ func (c *Config) MapToMap(pointer interface{}, mapping ...map[string]string) err if j := c.getJson(); j != nil { return j.MapToMap(pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // MapToMaps converts current Json object to specified map variable slice. @@ -385,7 +386,7 @@ func (c *Config) MapToMaps(pointer interface{}, mapping ...map[string]string) er if j := c.getJson(); j != nil { return j.MapToMaps(pointer, mapping...) } - return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found") + return gerror.NewCode(gcode.CodeMissingConfiguration, "configuration not found") } // Clear removes all parsed configuration files content cache, diff --git a/os/gcmd/gcmd_handler.go b/os/gcmd/gcmd_handler.go index a0a4b4c8c..9853a2019 100644 --- a/os/gcmd/gcmd_handler.go +++ b/os/gcmd/gcmd_handler.go @@ -8,13 +8,14 @@ package gcmd import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" ) // BindHandle registers callback function <f> with <cmd>. func BindHandle(cmd string, f func()) error { if _, ok := defaultCommandFuncMap[cmd]; ok { - return gerror.NewCode(gerror.CodeInvalidOperation, "duplicated handle for command:"+cmd) + return gerror.NewCode(gcode.CodeInvalidOperation, "duplicated handle for command:"+cmd) } else { defaultCommandFuncMap[cmd] = f } @@ -37,7 +38,7 @@ func RunHandle(cmd string) error { if handle, ok := defaultCommandFuncMap[cmd]; ok { handle() } else { - return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd) + return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd) } return nil } @@ -49,10 +50,10 @@ func AutoRun() error { if handle, ok := defaultCommandFuncMap[cmd]; ok { handle() } else { - return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd) + return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd) } } else { - return gerror.NewCode(gerror.CodeMissingParameter, "no command found") + return gerror.NewCode(gcode.CodeMissingParameter, "no command found") } return nil } diff --git a/os/gcmd/gcmd_parser.go b/os/gcmd/gcmd_parser.go index e6b20b804..a53868746 100644 --- a/os/gcmd/gcmd_parser.go +++ b/os/gcmd/gcmd_parser.go @@ -8,6 +8,7 @@ package gcmd import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "os" @@ -94,7 +95,7 @@ func ParseWithArgs(args []string, supportedOptions map[string]bool, strict ...bo i++ continue } else if parser.strict { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid option '%s'`, args[i]) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid option '%s'`, args[i]) } } } diff --git a/os/gcmd/gcmd_parser_handler.go b/os/gcmd/gcmd_parser_handler.go index 03e1ed093..c30ecbdad 100644 --- a/os/gcmd/gcmd_parser_handler.go +++ b/os/gcmd/gcmd_parser_handler.go @@ -8,13 +8,14 @@ package gcmd import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" ) // BindHandle registers callback function <f> with <cmd>. func (p *Parser) BindHandle(cmd string, f func()) error { if _, ok := p.commandFuncMap[cmd]; ok { - return gerror.NewCode(gerror.CodeInvalidOperation, "duplicated handle for command:"+cmd) + return gerror.NewCode(gcode.CodeInvalidOperation, "duplicated handle for command:"+cmd) } else { p.commandFuncMap[cmd] = f } @@ -37,7 +38,7 @@ func (p *Parser) RunHandle(cmd string) error { if handle, ok := p.commandFuncMap[cmd]; ok { handle() } else { - return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd) + return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd) } return nil } @@ -49,10 +50,10 @@ func (p *Parser) AutoRun() error { if handle, ok := p.commandFuncMap[cmd]; ok { handle() } else { - return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd) + return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd) } } else { - return gerror.NewCode(gerror.CodeMissingParameter, "no command found") + return gerror.NewCode(gcode.CodeMissingParameter, "no command found") } return nil } diff --git a/os/gcron/gcron_entry.go b/os/gcron/gcron_entry.go index 81ed8a778..60aa64931 100644 --- a/os/gcron/gcron_entry.go +++ b/os/gcron/gcron_entry.go @@ -43,7 +43,7 @@ type addEntryInput struct { func (c *Cron) doAddEntry(in addEntryInput) (*Entry, error) { if in.Name != "" { if c.Search(in.Name) != nil { - return nil, gerror.NewCodef(gerror.CodeInvalidOperation, `cron job "%s" already exists`, in.Name) + return nil, gerror.NewCodef(gcode.CodeInvalidOperation, `cron job "%s" already exists`, in.Name) } } diff --git a/os/gcron/gcron_schedule.go b/os/gcron/gcron_schedule.go index 0fdd83206..0b92fec15 100644 --- a/os/gcron/gcron_schedule.go +++ b/os/gcron/gcron_schedule.go @@ -90,7 +90,7 @@ func newSchedule(pattern string) (*cronSchedule, error) { }, nil } } else { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern: "%s"`, pattern) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern: "%s"`, pattern) } } // Handle the common cron pattern, like: @@ -139,7 +139,7 @@ func newSchedule(pattern string) (*cronSchedule, error) { } return schedule, nil } else { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern: "%s"`, pattern) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern: "%s"`, pattern) } } @@ -156,7 +156,7 @@ func parseItem(item string, min int, max int, allowQuestionMark bool) (map[int]s intervalArray := strings.Split(item, "/") if len(intervalArray) == 2 { if i, err := strconv.Atoi(intervalArray[1]); err != nil { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern item: "%s"`, item) } else { interval = i } @@ -178,7 +178,7 @@ func parseItem(item string, min int, max int, allowQuestionMark bool) (map[int]s // Eg: */5 if rangeArray[0] != "*" { if i, err := parseItemValue(rangeArray[0], fieldType); err != nil { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern item: "%s"`, item) } else { rangeMin = i rangeMax = i @@ -186,7 +186,7 @@ func parseItem(item string, min int, max int, allowQuestionMark bool) (map[int]s } if len(rangeArray) == 2 { if i, err := parseItemValue(rangeArray[1], fieldType); err != nil { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern item: "%s"`, item) } else { rangeMax = i } @@ -220,7 +220,7 @@ func parseItemValue(value string, fieldType byte) (int, error) { } } } - return 0, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern value: "%s"`, value) + return 0, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid pattern value: "%s"`, value) } // meet checks if the given time `t` meets the runnable point for the job. diff --git a/os/gfile/gfile_copy.go b/os/gfile/gfile_copy.go index b8f30c68e..26ace7bcf 100644 --- a/os/gfile/gfile_copy.go +++ b/os/gfile/gfile_copy.go @@ -8,6 +8,7 @@ package gfile import ( "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "io" "io/ioutil" @@ -21,10 +22,10 @@ import ( // or else it calls CopyDir. func Copy(src string, dst string) error { if src == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "source path cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "source path cannot be empty") } if dst == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "destination path cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "destination path cannot be empty") } if IsFile(src) { return CopyFile(src, dst) @@ -40,10 +41,10 @@ func Copy(src string, dst string) error { // Thanks: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04 func CopyFile(src, dst string) (err error) { if src == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "source file cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "source file cannot be empty") } if dst == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "destination file cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "destination file cannot be empty") } // If src and dst are the same path, it does nothing. if src == dst { @@ -87,10 +88,10 @@ func CopyFile(src, dst string) (err error) { // Note that, the Source directory must exist and symlinks are ignored and skipped. func CopyDir(src string, dst string) (err error) { if src == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "source directory cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "source directory cannot be empty") } if dst == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "destination directory cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "destination directory cannot be empty") } // If src and dst are the same path, it does nothing. if src == dst { diff --git a/os/gfile/gfile_home.go b/os/gfile/gfile_home.go index 15819b550..44e0da4ad 100644 --- a/os/gfile/gfile_home.go +++ b/os/gfile/gfile_home.go @@ -8,6 +8,7 @@ package gfile import ( "bytes" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "os" "os/exec" @@ -56,7 +57,7 @@ func homeUnix() (string, error) { result := strings.TrimSpace(stdout.String()) if result == "" { - return "", gerror.NewCode(gerror.CodeInternalError, "blank output when reading home directory") + return "", gerror.NewCode(gcode.CodeInternalError, "blank output when reading home directory") } return result, nil @@ -73,7 +74,7 @@ func homeWindows() (string, error) { home = os.Getenv("USERPROFILE") } if home == "" { - return "", gerror.NewCode(gerror.CodeOperationFailed, "HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") + return "", gerror.NewCode(gcode.CodeOperationFailed, "HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") } return home, nil diff --git a/os/gfile/gfile_scan.go b/os/gfile/gfile_scan.go index a14672fe9..05f46aee8 100644 --- a/os/gfile/gfile_scan.go +++ b/os/gfile/gfile_scan.go @@ -7,6 +7,7 @@ package gfile import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/text/gstr" "os" @@ -137,7 +138,7 @@ func ScanDirFileFunc(path string, pattern string, recursive bool, handler func(p // string, or else it appends the sub-file path to result slice. func doScanDir(depth int, path string, pattern string, recursive bool, handler func(path string) string) ([]string, error) { if depth >= maxScanDepth { - return nil, gerror.NewCodef(gerror.CodeOperationFailed, "directory scanning exceeds max recursive depth: %d", maxScanDepth) + return nil, gerror.NewCodef(gcode.CodeOperationFailed, "directory scanning exceeds max recursive depth: %d", maxScanDepth) } list := ([]string)(nil) file, err := os.Open(path) diff --git a/os/gfile/gfile_search.go b/os/gfile/gfile_search.go index 7dcc9d77d..97ab2deac 100644 --- a/os/gfile/gfile_search.go +++ b/os/gfile/gfile_search.go @@ -9,6 +9,7 @@ package gfile import ( "bytes" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/container/garray" @@ -52,7 +53,7 @@ func Search(name string, prioritySearchPaths ...string) (realPath string, err er buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v)) } }) - err = gerror.NewCode(gerror.CodeOperationFailed, buffer.String()) + err = gerror.NewCode(gcode.CodeOperationFailed, buffer.String()) } return } diff --git a/os/gfpool/gfpool_file.go b/os/gfpool/gfpool_file.go index aab691279..9519322e2 100644 --- a/os/gfpool/gfpool_file.go +++ b/os/gfpool/gfpool_file.go @@ -8,6 +8,7 @@ package gfpool import ( "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "os" "time" @@ -41,7 +42,7 @@ func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file * // Stat returns the FileInfo structure describing file. func (f *File) Stat() (os.FileInfo, error) { if f.stat == nil { - return nil, gerror.NewCode(gerror.CodeInternalError, "file stat is empty") + return nil, gerror.NewCode(gcode.CodeInternalError, "file stat is empty") } return f.stat, nil } diff --git a/os/gfsnotify/gfsnotify.go b/os/gfsnotify/gfsnotify.go index 89fb6b958..e66377d2c 100644 --- a/os/gfsnotify/gfsnotify.go +++ b/os/gfsnotify/gfsnotify.go @@ -10,6 +10,7 @@ package gfsnotify import ( "context" "github.com/gogf/gf/container/gset" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "sync" @@ -139,7 +140,7 @@ func RemoveCallback(callbackId int) error { callback = r.(*Callback) } if callback == nil { - return gerror.NewCodef(gerror.CodeInvalidParameter, `callback for id %d not found`, callbackId) + return gerror.NewCodef(gcode.CodeInvalidParameter, `callback for id %d not found`, callbackId) } w.RemoveCallback(callbackId) return nil diff --git a/os/gfsnotify/gfsnotify_watcher.go b/os/gfsnotify/gfsnotify_watcher.go index af6c2ff22..810e8c1aa 100644 --- a/os/gfsnotify/gfsnotify_watcher.go +++ b/os/gfsnotify/gfsnotify_watcher.go @@ -8,6 +8,7 @@ package gfsnotify import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" @@ -66,7 +67,7 @@ func (w *Watcher) AddOnce(name, path string, callbackFunc func(event *Event), re func (w *Watcher) addWithCallbackFunc(name, path string, callbackFunc func(event *Event), recursive ...bool) (callback *Callback, err error) { // Check and convert the given path to absolute path. if t := fileRealPath(path); t == "" { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `"%s" does not exist`, path) } else { path = t } diff --git a/os/glog/glog_logger_config.go b/os/glog/glog_logger_config.go index 1ed493531..a14181e67 100644 --- a/os/glog/glog_logger_config.go +++ b/os/glog/glog_logger_config.go @@ -7,6 +7,7 @@ package glog import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/os/gctx" "io" "strings" @@ -83,7 +84,7 @@ func (l *Logger) SetConfig(config Config) error { // SetConfigWithMap set configurations with map for the logger. func (l *Logger) SetConfigWithMap(m map[string]interface{}) error { if m == nil || len(m) == 0 { - return gerror.NewCode(gerror.CodeInvalidParameter, "configuration cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "configuration cannot be empty") } // The m now is a shallow copy of m. // A little tricky, isn't it? @@ -94,7 +95,7 @@ func (l *Logger) SetConfigWithMap(m map[string]interface{}) error { if level, ok := levelStringMap[strings.ToUpper(gconv.String(levelValue))]; ok { m[levelKey] = level } else { - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid level string: %v`, levelValue) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid level string: %v`, levelValue) } } // Change string configuration to int value for file rotation size. @@ -102,7 +103,7 @@ func (l *Logger) SetConfigWithMap(m map[string]interface{}) error { if rotateSizeValue != nil { m[rotateSizeKey] = gfile.StrToSize(gconv.String(rotateSizeValue)) if m[rotateSizeKey] == -1 { - return gerror.NewCodef(gerror.CodeInvalidConfiguration, `invalid rotate size: %v`, rotateSizeValue) + return gerror.NewCodef(gcode.CodeInvalidConfiguration, `invalid rotate size: %v`, rotateSizeValue) } } if err := gconv.Struct(m, &l.config); err != nil { @@ -208,11 +209,11 @@ func (l *Logger) GetWriter() io.Writer { // SetPath sets the directory path for file logging. func (l *Logger) SetPath(path string) error { if path == "" { - return gerror.NewCode(gerror.CodeInvalidParameter, "logging path is empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "logging path is empty") } if !gfile.Exists(path) { if err := gfile.Mkdir(path); err != nil { - return gerror.WrapCodef(gerror.CodeOperationFailed, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd()) + return gerror.WrapCodef(gcode.CodeOperationFailed, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd()) } } l.config.Path = strings.TrimRight(path, gfile.Separator) diff --git a/os/glog/glog_logger_level.go b/os/glog/glog_logger_level.go index 88c2e374d..5d9b0ad5d 100644 --- a/os/glog/glog_logger_level.go +++ b/os/glog/glog_logger_level.go @@ -7,6 +7,7 @@ package glog import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "strings" ) @@ -77,7 +78,7 @@ func (l *Logger) SetLevelStr(levelStr string) error { if level, ok := levelStringMap[strings.ToUpper(levelStr)]; ok { l.config.Level = level } else { - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid level string: %s`, levelStr) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid level string: %s`, levelStr) } return nil } diff --git a/os/gproc/gproc_comm.go b/os/gproc/gproc_comm.go index 9d2bf6aa5..51a40f2bd 100644 --- a/os/gproc/gproc_comm.go +++ b/os/gproc/gproc_comm.go @@ -9,6 +9,7 @@ package gproc import ( "fmt" "github.com/gogf/gf/container/gmap" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/net/gtcp" "github.com/gogf/gf/os/gfile" @@ -65,7 +66,7 @@ func getConnByPid(pid int) (*gtcp.PoolConn, error) { return nil, err } } - return nil, gerror.NewCodef(gerror.CodeOperationFailed, "could not find port for pid: %d", pid) + return nil, gerror.NewCodef(gcode.CodeOperationFailed, "could not find port for pid: %d", pid) } // getPortByPid returns the listening port for specified pid. diff --git a/os/gproc/gproc_process.go b/os/gproc/gproc_process.go index 625407364..a560c0eb8 100644 --- a/os/gproc/gproc_process.go +++ b/os/gproc/gproc_process.go @@ -9,6 +9,7 @@ package gproc import ( "context" "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "os" @@ -101,7 +102,7 @@ func (p *Process) Send(data []byte) error { if p.Process != nil { return Send(p.Process.Pid, data) } - return gerror.NewCode(gerror.CodeInvalidParameter, "invalid process") + return gerror.NewCode(gcode.CodeInvalidParameter, "invalid process") } // Release releases any resources associated with the Process p, diff --git a/os/grpool/grpool.go b/os/grpool/grpool.go index 08d6134cf..f9c19c356 100644 --- a/os/grpool/grpool.go +++ b/os/grpool/grpool.go @@ -8,6 +8,7 @@ package grpool import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/container/glist" @@ -69,7 +70,7 @@ func Jobs() int { // The job will be executed asynchronously. func (p *Pool) Add(f func()) error { for p.closed.Val() { - return gerror.NewCode(gerror.CodeInvalidOperation, "pool closed") + return gerror.NewCode(gcode.CodeInvalidOperation, "pool closed") } p.list.PushFront(f) // Check whether fork new goroutine or not. @@ -101,7 +102,7 @@ func (p *Pool) AddWithRecover(userFunc func(), recoverFunc ...func(err error)) e if err, ok := exception.(error); ok { recoverFunc[0](err) } else { - recoverFunc[0](gerror.NewCodef(gerror.CodeInternalError, `%v`, exception)) + recoverFunc[0](gerror.NewCodef(gcode.CodeInternalError, `%v`, exception)) } } } diff --git a/os/gsession/gsession.go b/os/gsession/gsession.go index 16b901808..ee1d15fc9 100644 --- a/os/gsession/gsession.go +++ b/os/gsession/gsession.go @@ -8,6 +8,7 @@ package gsession import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/util/guid" ) @@ -15,7 +16,7 @@ import ( var ( ErrorDisabled = gerror.NewOption(gerror.Option{ Text: "this feature is disabled in this storage", - Code: gerror.CodeNotSupported, + Code: gcode.CodeNotSupported, }) ) diff --git a/os/gsession/gsession_session.go b/os/gsession/gsession_session.go index 7dcab726f..edc70ff9d 100644 --- a/os/gsession/gsession_session.go +++ b/os/gsession/gsession_session.go @@ -8,6 +8,7 @@ package gsession import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "time" @@ -187,7 +188,7 @@ func (s *Session) Id() string { // It returns error if it is called after session starts. func (s *Session) SetId(id string) error { if s.start { - return gerror.NewCode(gerror.CodeInvalidOperation, "session already started") + return gerror.NewCode(gcode.CodeInvalidOperation, "session already started") } s.id = id return nil @@ -197,7 +198,7 @@ func (s *Session) SetId(id string) error { // It returns error if it is called after session starts. func (s *Session) SetIdFunc(f func(ttl time.Duration) string) error { if s.start { - return gerror.NewCode(gerror.CodeInvalidOperation, "session already started") + return gerror.NewCode(gcode.CodeInvalidOperation, "session already started") } s.idFunc = f return nil diff --git a/os/gsession/gsession_storage_file.go b/os/gsession/gsession_storage_file.go index 641ad9912..12fd4e2af 100644 --- a/os/gsession/gsession_storage_file.go +++ b/os/gsession/gsession_storage_file.go @@ -9,6 +9,7 @@ package gsession import ( "context" "github.com/gogf/gf/container/gmap" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/internal/json" @@ -48,15 +49,15 @@ func NewStorageFile(path ...string) *StorageFile { if len(path) > 0 && path[0] != "" { storagePath, _ = gfile.Search(path[0]) if storagePath == "" { - panic(gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path[0])) + panic(gerror.NewCodef(gcode.CodeInvalidParameter, `"%s" does not exist`, path[0])) } if !gfile.IsWritable(storagePath) { - panic(gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" is not writable`, path[0])) + panic(gerror.NewCodef(gcode.CodeInvalidParameter, `"%s" is not writable`, path[0])) } } if storagePath != "" { if err := gfile.Mkdir(storagePath); err != nil { - panic(gerror.WrapCodef(gerror.CodeInternalError, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd())) + panic(gerror.WrapCodef(gcode.CodeInternalError, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd())) } } s := &StorageFile{ diff --git a/os/gspath/gspath.go b/os/gspath/gspath.go index 2e7394086..fb0a8818d 100644 --- a/os/gspath/gspath.go +++ b/os/gspath/gspath.go @@ -13,6 +13,7 @@ package gspath import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "os" @@ -103,7 +104,7 @@ func (sp *SPath) Set(path string) (realPath string, err error) { } } if realPath == "" { - return realPath, gerror.NewCodef(gerror.CodeInvalidParameter, `path "%s" does not exist`, path) + return realPath, gerror.NewCodef(gcode.CodeInvalidParameter, `path "%s" does not exist`, path) } // The set path must be a directory. if gfile.IsDir(realPath) { @@ -123,7 +124,7 @@ func (sp *SPath) Set(path string) (realPath string, err error) { sp.addMonitorByPath(realPath) return realPath, nil } else { - return "", gerror.NewCode(gerror.CodeInvalidParameter, path+" should be a folder") + return "", gerror.NewCode(gcode.CodeInvalidParameter, path+" should be a folder") } } @@ -138,7 +139,7 @@ func (sp *SPath) Add(path string) (realPath string, err error) { } } if realPath == "" { - return realPath, gerror.NewCodef(gerror.CodeInvalidParameter, `path "%s" does not exist`, path) + return realPath, gerror.NewCodef(gcode.CodeInvalidParameter, `path "%s" does not exist`, path) } // The added path must be a directory. if gfile.IsDir(realPath) { @@ -152,7 +153,7 @@ func (sp *SPath) Add(path string) (realPath string, err error) { } return realPath, nil } else { - return "", gerror.NewCode(gerror.CodeInvalidParameter, path+" should be a folder") + return "", gerror.NewCode(gcode.CodeInvalidParameter, path+" should be a folder") } } diff --git a/os/gtime/gtime.go b/os/gtime/gtime.go index 3cb587369..cb164da44 100644 --- a/os/gtime/gtime.go +++ b/os/gtime/gtime.go @@ -11,6 +11,7 @@ package gtime import ( "fmt" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/utils" "os" @@ -277,7 +278,7 @@ func StrToTime(str string, format ...string) (*Time, error) { } return NewFromTime(time.Date(0, time.Month(1), 1, hour, min, sec, nsec, local)), nil } else { - return nil, gerror.NewCode(gerror.CodeInvalidParameter, "unsupported time format") + return nil, gerror.NewCode(gcode.CodeInvalidParameter, "unsupported time format") } // Time @@ -312,7 +313,7 @@ func StrToTime(str string, format ...string) (*Time, error) { m, _ := strconv.Atoi(zone[2:4]) s, _ := strconv.Atoi(zone[4:6]) if h > 24 || m > 59 || s > 59 { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, "invalid zone string: %s", match[6]) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, "invalid zone string: %s", match[6]) } // Comparing the given time zone whether equals to current time zone, // it converts it to UTC if they does not equal. @@ -351,7 +352,7 @@ func StrToTime(str string, format ...string) (*Time, error) { } } if month <= 0 || day <= 0 { - return nil, gerror.NewCodef(gerror.CodeInvalidParameter, "invalid time string:%s", str) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, "invalid time string:%s", str) } return NewFromTime(time.Date(year, time.Month(month), day, hour, min, sec, nsec, local)), nil } diff --git a/os/gtime/gtime_time.go b/os/gtime/gtime_time.go index 785e34a84..185c9dbd9 100644 --- a/os/gtime/gtime_time.go +++ b/os/gtime/gtime_time.go @@ -8,6 +8,7 @@ package gtime import ( "bytes" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "strconv" "time" @@ -462,7 +463,7 @@ func (t *Time) UnmarshalText(data []byte) error { *t = *vTime return nil } - return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid time value: %s`, data) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid time value: %s`, data) } // NoValidation marks this struct object will not be validated by package gvalid. diff --git a/os/gview/gview_config.go b/os/gview/gview_config.go index 0bba3cf4b..79dd6eced 100644 --- a/os/gview/gview_config.go +++ b/os/gview/gview_config.go @@ -8,6 +8,7 @@ package gview import ( "context" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/i18n/gi18n" "github.com/gogf/gf/internal/intlog" @@ -74,7 +75,7 @@ func (view *View) SetConfig(config Config) error { // SetConfigWithMap set configurations with map for the view. func (view *View) SetConfigWithMap(m map[string]interface{}) error { if m == nil || len(m) == 0 { - return gerror.NewCode(gerror.CodeInvalidParameter, "configuration cannot be empty") + return gerror.NewCode(gcode.CodeInvalidParameter, "configuration cannot be empty") } // The m now is a shallow copy of m. // Any changes to m does not affect the original one. @@ -123,7 +124,7 @@ func (view *View) SetPath(path string) error { } // Path not exist. if realPath == "" { - err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] SetPath failed: path "%s" does not exist`, path) + err := gerror.NewCodef(gcode.CodeInvalidParameter, `[gview] SetPath failed: path "%s" does not exist`, path) if errorPrint() { glog.Error(err) } @@ -131,7 +132,7 @@ func (view *View) SetPath(path string) error { } // Should be a directory. if !isDir { - err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] SetPath failed: path "%s" should be directory type`, path) + err := gerror.NewCodef(gcode.CodeInvalidParameter, `[gview] SetPath failed: path "%s" should be directory type`, path) if errorPrint() { glog.Error(err) } @@ -177,7 +178,7 @@ func (view *View) AddPath(path string) error { } // Path not exist. if realPath == "" { - err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] AddPath failed: path "%s" does not exist`, path) + err := gerror.NewCodef(gcode.CodeInvalidParameter, `[gview] AddPath failed: path "%s" does not exist`, path) if errorPrint() { glog.Error(err) } @@ -185,7 +186,7 @@ func (view *View) AddPath(path string) error { } // realPath should be type of folder. if !isDir { - err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] AddPath failed: path "%s" should be directory type`, path) + err := gerror.NewCodef(gcode.CodeInvalidParameter, `[gview] AddPath failed: path "%s" should be directory type`, path) if errorPrint() { glog.Error(err) } diff --git a/os/gview/gview_parse.go b/os/gview/gview_parse.go index f4da300fa..cd50e7a8b 100644 --- a/os/gview/gview_parse.go +++ b/os/gview/gview_parse.go @@ -11,6 +11,7 @@ import ( "context" "fmt" "github.com/gogf/gf/encoding/ghash" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/os/gfsnotify" @@ -112,7 +113,7 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res tpl, err = tpl.(*texttpl.Template).Parse(item.content) } if err != nil && item.path != "" { - err = gerror.WrapCode(gerror.CodeInternalError, err, item.path) + err = gerror.WrapCode(gcode.CodeInternalError, err, item.path) } }) if err != nil { @@ -298,7 +299,7 @@ func (view *View) getTemplate(filePath, folderPath, pattern string) (tpl interfa // formatTemplateObjectCreatingError formats the error that creted from creating template object. func (view *View) formatTemplateObjectCreatingError(filePath, tplName string, err error) error { if err != nil { - return gerror.NewCodeSkip(gerror.CodeInternalError, 1, gstr.Replace(err.Error(), tplName, filePath)) + return gerror.NewCodeSkip(gcode.CodeInternalError, 1, gstr.Replace(err.Error(), tplName, filePath)) } return nil } @@ -376,7 +377,7 @@ func (view *View) searchFile(file string) (path string, folder string, resource if errorPrint() { glog.Error(buffer.String()) } - err = gerror.NewCodef(gerror.CodeInvalidParameter, `template file "%s" not found`, file) + err = gerror.NewCodef(gcode.CodeInvalidParameter, `template file "%s" not found`, file) } return } diff --git a/util/gconv/gconv_maptomap.go b/util/gconv/gconv_maptomap.go index 22524ba9e..973f12e52 100644 --- a/util/gconv/gconv_maptomap.go +++ b/util/gconv/gconv_maptomap.go @@ -7,6 +7,7 @@ package gconv import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "reflect" @@ -90,7 +91,7 @@ func doMapToMap(params interface{}, pointer interface{}, mapping ...map[string]s pointerKind = pointerRv.Kind() } if pointerKind != reflect.Map { - return gerror.NewCodef(gerror.CodeInvalidParameter, "pointer should be type of *map, but got:%s", pointerKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "pointer should be type of *map, but got:%s", pointerKind) } defer func() { // Catch the panic, especially the reflect operation panics. @@ -98,7 +99,7 @@ func doMapToMap(params interface{}, pointer interface{}, mapping ...map[string]s if e, ok := exception.(errorStack); ok { err = e } else { - err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception) + err = gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%v", exception) } } }() diff --git a/util/gconv/gconv_maptomaps.go b/util/gconv/gconv_maptomaps.go index b37e1ac31..a3c0928b5 100644 --- a/util/gconv/gconv_maptomaps.go +++ b/util/gconv/gconv_maptomaps.go @@ -7,6 +7,7 @@ package gconv import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "reflect" @@ -73,7 +74,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] paramsKind = paramsRv.Kind() } if paramsKind != reflect.Array && paramsKind != reflect.Slice { - return gerror.NewCode(gerror.CodeInvalidParameter, "params should be type of slice, eg: []map/[]*map/[]struct/[]*struct") + return gerror.NewCode(gcode.CodeInvalidParameter, "params should be type of slice, eg: []map/[]*map/[]struct/[]*struct") } var ( paramsElem = paramsRv.Type().Elem() @@ -84,7 +85,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] paramsElemKind = paramsElem.Kind() } if paramsElemKind != reflect.Map && paramsElemKind != reflect.Struct && paramsElemKind != reflect.Interface { - return gerror.NewCodef(gerror.CodeInvalidParameter, "params element should be type of map/*map/struct/*struct, but got: %s", paramsElemKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "params element should be type of map/*map/struct/*struct, but got: %s", paramsElemKind) } // Empty slice, no need continue. if paramsRv.Len() == 0 { @@ -100,7 +101,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] pointerKind = pointerRv.Kind() } if pointerKind != reflect.Array && pointerKind != reflect.Slice { - return gerror.NewCode(gerror.CodeInvalidParameter, "pointer should be type of *[]map/*[]*map") + return gerror.NewCode(gcode.CodeInvalidParameter, "pointer should be type of *[]map/*[]*map") } var ( pointerElemType = pointerRv.Type().Elem() @@ -110,7 +111,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] pointerElemKind = pointerElemType.Elem().Kind() } if pointerElemKind != reflect.Map { - return gerror.NewCode(gerror.CodeInvalidParameter, "pointer element should be type of map/*map") + return gerror.NewCode(gcode.CodeInvalidParameter, "pointer element should be type of map/*map") } defer func() { // Catch the panic, especially the reflect operation panics. @@ -118,7 +119,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] if e, ok := exception.(errorStack); ok { err = e } else { - err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception) + err = gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%v", exception) } } }() diff --git a/util/gconv/gconv_scan.go b/util/gconv/gconv_scan.go index bb5af1f47..9f32740b0 100644 --- a/util/gconv/gconv_scan.go +++ b/util/gconv/gconv_scan.go @@ -7,6 +7,7 @@ package gconv import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "reflect" ) @@ -29,11 +30,11 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) pointerType = reflect.TypeOf(pointer) } if pointerType == nil { - return gerror.NewCode(gerror.CodeInvalidParameter, "parameter pointer should not be nil") + return gerror.NewCode(gcode.CodeInvalidParameter, "parameter pointer should not be nil") } pointerKind = pointerType.Kind() if pointerKind != reflect.Ptr { - return gerror.NewCodef(gerror.CodeInvalidParameter, "params should be type of pointer, but got type: %v", pointerKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got type: %v", pointerKind) } var ( pointerElem = pointerType.Elem() @@ -77,7 +78,7 @@ func ScanDeep(params interface{}, pointer interface{}, mapping ...map[string]str t := reflect.TypeOf(pointer) k := t.Kind() if k != reflect.Ptr { - return gerror.NewCodef(gerror.CodeInvalidParameter, "params should be type of pointer, but got: %v", k) + return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", k) } switch t.Elem().Kind() { case reflect.Array, reflect.Slice: diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index 381a75d28..bb959daa1 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -7,6 +7,7 @@ package gconv import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/empty" "github.com/gogf/gf/internal/json" @@ -58,7 +59,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string return nil } if pointer == nil { - return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil") + return gerror.NewCode(gcode.CodeInvalidParameter, "object pointer cannot be nil") } defer func() { @@ -67,7 +68,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string if e, ok := exception.(errorStack); ok { err = e } else { - err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception) + err = gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%v", exception) } } }() @@ -120,11 +121,11 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string pointerReflectValue = reflect.ValueOf(pointer) pointerReflectKind = pointerReflectValue.Kind() if pointerReflectKind != reflect.Ptr { - return gerror.NewCodef(gerror.CodeInvalidParameter, "object pointer should be type of '*struct', but got '%v'", pointerReflectKind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "object pointer should be type of '*struct', but got '%v'", pointerReflectKind) } // Using IsNil on reflect.Ptr variable is OK. if !pointerReflectValue.IsValid() || pointerReflectValue.IsNil() { - return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil") + return gerror.NewCode(gcode.CodeInvalidParameter, "object pointer cannot be nil") } pointerElemReflectValue = pointerReflectValue.Elem() } @@ -162,7 +163,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string // DO NOT use MapDeep here. paramsMap := Map(paramsInterface) if paramsMap == nil { - return gerror.NewCodef(gerror.CodeInvalidParameter, "convert params to map failed: %v", params) + return gerror.NewCodef(gcode.CodeInvalidParameter, "convert params to map failed: %v", params) } // It only performs one converting to the same attribute. @@ -303,7 +304,7 @@ func bindVarToStructAttr(elem reflect.Value, name string, value interface{}, map defer func() { if exception := recover(); exception != nil { if err = bindVarToReflectValue(structFieldValue, value, mapping, priorityTag); err != nil { - err = gerror.WrapCodef(gerror.CodeInternalError, err, `error binding value to attribute "%s"`, name) + err = gerror.WrapCodef(gcode.CodeInternalError, err, `error binding value to attribute "%s"`, name) } } }() @@ -484,7 +485,7 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}, ma defer func() { if exception := recover(); exception != nil { err = gerror.NewCodef( - gerror.CodeInternalError, + gcode.CodeInternalError, `cannot convert value "%+v" to type "%s":%+v`, value, structFieldValue.Type().String(), diff --git a/util/gconv/gconv_structs.go b/util/gconv/gconv_structs.go index cf2ac64a0..2bb370af8 100644 --- a/util/gconv/gconv_structs.go +++ b/util/gconv/gconv_structs.go @@ -7,6 +7,7 @@ package gconv import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/json" "reflect" @@ -48,7 +49,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin return nil } if pointer == nil { - return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil") + return gerror.NewCode(gcode.CodeInvalidParameter, "object pointer cannot be nil") } if doStructsByDirectReflectSet(params, pointer) { @@ -61,7 +62,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin if e, ok := exception.(errorStack); ok { err = e } else { - err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception) + err = gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%v", exception) } } }() @@ -93,7 +94,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin if !ok { pointerRv = reflect.ValueOf(pointer) if kind := pointerRv.Kind(); kind != reflect.Ptr { - return gerror.NewCodef(gerror.CodeInvalidParameter, "pointer should be type of pointer, but got: %v", kind) + return gerror.NewCodef(gcode.CodeInvalidParameter, "pointer should be type of pointer, but got: %v", kind) } } // Converting `params` to map slice. diff --git a/util/gvalid/gvalid_error.go b/util/gvalid/gvalid_error.go index 4f4a93fef..5fe38875c 100644 --- a/util/gvalid/gvalid_error.go +++ b/util/gvalid/gvalid_error.go @@ -7,6 +7,7 @@ package gvalid import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/text/gregex" "github.com/gogf/gf/text/gstr" @@ -15,7 +16,7 @@ import ( // Error is the validation error for validation result. type Error interface { - Code() int + Code() gcode.Code Current() error Error() string FirstItem() (key string, messages map[string]string) @@ -30,7 +31,7 @@ type Error interface { // validationError is the validation error for validation result. type validationError struct { - code int // Error code. + code gcode.Code // Error code. rules []fieldRule // Rules by sequence, which is used for keeping error sequence. errors map[string]map[string]string // Error map:map[field]map[rule]message firstKey string // The first error rule key(empty in default). @@ -38,7 +39,7 @@ type validationError struct { } // newError creates and returns a validation error. -func newError(code int, rules []fieldRule, errors map[string]map[string]string) *validationError { +func newError(code gcode.Code, rules []fieldRule, errors map[string]map[string]string) *validationError { for field, m := range errors { for k, v := range m { v = strings.Replace(v, ":attribute", field, -1) @@ -57,7 +58,7 @@ func newError(code int, rules []fieldRule, errors map[string]map[string]string) // newErrorStr creates and returns a validation error by string. func newErrorStr(key, err string) *validationError { - return newError(gerror.CodeInternalError, nil, map[string]map[string]string{ + return newError(gcode.CodeInternalError, nil, map[string]map[string]string{ internalErrorMapKey: { key: err, }, @@ -65,9 +66,9 @@ func newErrorStr(key, err string) *validationError { } // Code returns the error code of current validation error. -func (e *validationError) Code() int { +func (e *validationError) Code() gcode.Code { if e == nil { - return gerror.CodeNil + return gcode.CodeNil } return e.code } diff --git a/util/gvalid/gvalid_validator_check_map.go b/util/gvalid/gvalid_validator_check_map.go index ccbc66bc9..9db900232 100644 --- a/util/gvalid/gvalid_validator_check_map.go +++ b/util/gvalid/gvalid_validator_check_map.go @@ -7,7 +7,7 @@ package gvalid import ( - "github.com/gogf/gf/errors/gerror" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/util/gconv" "strings" ) @@ -149,7 +149,7 @@ func (v *Validator) doCheckMap(params interface{}) Error { } } if len(errorMaps) > 0 { - return newError(gerror.CodeValidationFailed, checkRules, errorMaps) + return newError(gcode.CodeValidationFailed, checkRules, errorMaps) } return nil } diff --git a/util/gvalid/gvalid_validator_check_struct.go b/util/gvalid/gvalid_validator_check_struct.go index 341afe542..78c4f9847 100644 --- a/util/gvalid/gvalid_validator_check_struct.go +++ b/util/gvalid/gvalid_validator_check_struct.go @@ -7,7 +7,7 @@ package gvalid import ( - "github.com/gogf/gf/errors/gerror" + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/internal/structs" "github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/gutil" @@ -288,7 +288,7 @@ func (v *Validator) doCheckStruct(object interface{}) Error { } } if len(errorMaps) > 0 { - return newError(gerror.CodeValidationFailed, checkRules, errorMaps) + return newError(gcode.CodeValidationFailed, checkRules, errorMaps) } return nil } diff --git a/util/gvalid/gvalid_validator_check_value.go b/util/gvalid/gvalid_validator_check_value.go index 6d8d99684..f02fff8a2 100644 --- a/util/gvalid/gvalid_validator_check_value.go +++ b/util/gvalid/gvalid_validator_check_value.go @@ -7,6 +7,7 @@ package gvalid import ( + "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "strconv" "strings" @@ -168,7 +169,7 @@ func (v *Validator) doCheckValue(input doCheckValueInput) Error { index++ } if len(errorMsgArray) > 0 { - return newError(gerror.CodeValidationFailed, []fieldRule{{Name: input.Name, Rule: input.Rule}}, map[string]map[string]string{ + return newError(gcode.CodeValidationFailed, []fieldRule{{Name: input.Name, Rule: input.Rule}}, map[string]map[string]string{ input.Name: errorMsgArray, }) } @@ -209,7 +210,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b if msg := v.checkLength(valueStr, input.RuleKey, input.RulePattern, input.CustomMsgMap); msg != "" { return match, gerror.NewOption(gerror.Option{ Text: msg, - Code: gerror.CodeValidationFailed, + Code: gcode.CodeValidationFailed, }) } else { match = true @@ -223,7 +224,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b if msg := v.checkRange(valueStr, input.RuleKey, input.RulePattern, input.CustomMsgMap); msg != "" { return match, gerror.NewOption(gerror.Option{ Text: msg, - Code: gerror.CodeValidationFailed, + Code: gcode.CodeValidationFailed, }) } else { match = true @@ -262,7 +263,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b msg = strings.Replace(msg, ":format", input.RulePattern, -1) return match, gerror.NewOption(gerror.Option{ Text: msg, - Code: gerror.CodeValidationFailed, + Code: gcode.CodeValidationFailed, }) } @@ -280,7 +281,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b msg = strings.Replace(msg, ":field", input.RulePattern, -1) return match, gerror.NewOption(gerror.Option{ Text: msg, - Code: gerror.CodeValidationFailed, + Code: gcode.CodeValidationFailed, }) } @@ -299,7 +300,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b msg = strings.Replace(msg, ":field", input.RulePattern, -1) return match, gerror.NewOption(gerror.Option{ Text: msg, - Code: gerror.CodeValidationFailed, + Code: gcode.CodeValidationFailed, }) } @@ -485,7 +486,7 @@ func (v *Validator) doCheckBuildInRules(input doCheckBuildInRulesInput) (match b default: return match, gerror.NewOption(gerror.Option{ Text: "Invalid rule name: " + input.RuleKey, - Code: gerror.CodeInvalidParameter, + Code: gcode.CodeInvalidParameter, }) } return match, nil diff --git a/util/gvalid/gvalid_z_unit_basic_all_test.go b/util/gvalid/gvalid_z_unit_basic_all_test.go index 2997913d2..23de12ab7 100755 --- a/util/gvalid/gvalid_z_unit_basic_all_test.go +++ b/util/gvalid/gvalid_z_unit_basic_all_test.go @@ -1019,12 +1019,12 @@ func Test_Code(t *testing.T) { gtest.C(t, func(t *gtest.T) { err := g.Validator().Rules("required").CheckValue("") t.AssertNE(err, nil) - t.Assert(gerror.Code(err), gerror.CodeValidationFailed) + t.Assert(gerror.Code(err), gcode.CodeValidationFailed) }) gtest.C(t, func(t *gtest.T) { err := g.Validator().Rules("none-exist-rule").CheckValue("") t.AssertNE(err, nil) - t.Assert(gerror.Code(err), gerror.CodeInternalError) + t.Assert(gerror.Code(err), gcode.CodeInternalError) }) }