add error code for components

This commit is contained in:
John Guo
2021-07-20 23:02:02 +08:00
parent f72d991c36
commit 0ddacdd7e2
88 changed files with 434 additions and 263 deletions

View File

@ -10,7 +10,6 @@ package gdb
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/gogf/gf/errors/gerror"
@ -333,7 +332,10 @@ func New(group ...string) (db DB, err error) {
defer configs.RUnlock()
if len(configs.config) < 1 {
return nil, gerror.New("database configuration is empty, please set the database configuration before using")
return nil, gerror.NewCode(
gerror.CodeInvalidConfiguration,
"database configuration is empty, please set the database configuration before using",
)
}
if _, ok := configs.config[groupName]; ok {
if node, err := getConfigNodeByGroup(groupName, true); err == nil {
@ -352,7 +354,8 @@ func New(group ...string) (db DB, err error) {
}
return c.db, nil
} else {
return nil, gerror.Newf(
return nil, gerror.NewCodef(
gerror.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,
)
@ -361,7 +364,8 @@ func New(group ...string) (db DB, err error) {
return nil, err
}
} else {
return nil, gerror.Newf(
return nil, gerror.NewCodef(
gerror.CodeInvalidConfiguration,
`database configuration node "%s" is not found, did you misspell group name "%s" or miss the database configuration?`,
groupName, groupName,
)
@ -404,7 +408,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) {
}
}
if len(masterList) < 1 {
return nil, gerror.New("at least one master node configuration's need to make sense")
return nil, gerror.NewCode(gerror.CodeInvalidConfiguration, "at least one master node configuration's need to make sense")
}
if len(slaveList) < 1 {
slaveList = masterList
@ -415,7 +419,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) {
return getConfigNodeByWeight(slaveList), nil
}
} else {
return nil, gerror.New(fmt.Sprintf("empty database configuration for item name '%s'", group))
return nil, gerror.NewCodef(gerror.CodeInvalidConfiguration, "empty database configuration for item name '%s'", group)
}
}

View File

@ -89,7 +89,7 @@ func (c *Core) GetCtxTimeout(timeoutType int, ctx context.Context) (context.Cont
return context.WithTimeout(ctx, c.db.GetConfig().PrepareTimeout)
}
default:
panic(gerror.Newf("invalid context timeout type: %d", timeoutType))
panic(gerror.NewCodef(gerror.CodeInvalidParameter, "invalid context timeout type: %d", timeoutType))
}
return ctx, func() {}
}
@ -553,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.New("data cannot be empty")
return nil, gerror.NewCode(gerror.CodeMissingParameter, "data cannot be empty")
}
if len(params) > 0 {
args = append(params, args...)

View File

@ -136,7 +136,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.New(ctxStrictErrorStr)
return sql, args, gerror.NewCode(gerror.CodeMissingParameter, ctxStrictErrorStr)
}
}
return sql, args, nil
@ -181,7 +181,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.New(ctxStrictErrorStr)
return nil, gerror.NewCode(gerror.CodeMissingParameter, ctxStrictErrorStr)
}
}

View File

@ -214,7 +214,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.New("function TableFields supports only single table operations")
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations")
}
useSchema := d.db.GetSchema()
if len(schema) > 0 && schema[0] != "" {
@ -292,10 +292,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.New(`Save operation is not supported by mssql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by mssql driver`)
case insertOptionReplace:
return nil, gerror.New(`Replace operation is not supported by mssql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by mssql driver`)
default:
return d.Core.DoInsert(ctx, link, table, list, option)

View File

@ -121,7 +121,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.New("function TableFields supports only single table operations")
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations")
}
useSchema := d.schema.Val()
if len(schema) > 0 && schema[0] != "" {

View File

@ -186,7 +186,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.New("function TableFields supports only single table operations")
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations")
}
useSchema := d.db.GetSchema()
if len(schema) > 0 && schema[0] != "" {
@ -278,10 +278,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.New(`Save operation is not supported by mssql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by mssql driver`)
case insertOptionReplace:
return nil, gerror.New(`Replace operation is not supported by mssql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by mssql driver`)
}
var (

View File

@ -126,7 +126,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.New("function TableFields supports only single table operations")
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations")
}
table, _ = gregex.ReplaceString("\"", "", table)
useSchema := d.db.GetSchema()
@ -190,10 +190,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.New(`Save operation is not supported by pgsql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by pgsql driver`)
case insertOptionReplace:
return nil, gerror.New(`Replace operation is not supported by pgsql driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by pgsql driver`)
default:
return d.Core.DoInsert(ctx, link, table, list, option)

View File

@ -99,7 +99,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.New("function TableFields supports only single table operations")
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "function TableFields supports only single table operations")
}
useSchema := d.db.GetSchema()
if len(schema) > 0 && schema[0] != "" {
@ -141,10 +141,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.New(`Save operation is not supported by sqlite driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Save operation is not supported by sqlite driver`)
case insertOptionReplace:
return nil, gerror.New(`Replace operation is not supported by sqlite driver`)
return nil, gerror.NewCode(gerror.CodeNotSupported, `Replace operation is not supported by sqlite driver`)
default:
return d.Core.DoInsert(ctx, link, table, list, option)

View File

@ -805,7 +805,7 @@ func handleArguments(sql string, args []interface{}) (newSql string, newArgs []i
// formatError customizes and returns the SQL error.
func formatError(err error, sql string, args ...interface{}) error {
if err != nil && err != ErrNoRows {
return gerror.New(fmt.Sprintf("%s, %s\n", err.Error(), FormatSqlWithArgs(sql, args)))
return gerror.NewCodef(gerror.CodeDbOperationError, "%s, %s\n", err.Error(), FormatSqlWithArgs(sql, args))
}
return err
}

View File

@ -44,7 +44,7 @@ func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
}
conditionStr := conditionWhere + conditionExtra
if !gstr.ContainsI(conditionStr, " WHERE ") {
return nil, gerror.New("there should be WHERE condition statement for DELETE operation")
return nil, gerror.NewCode(gerror.CodeMissingParameter, "there should be WHERE condition statement for DELETE operation")
}
return m.db.DoDelete(m.GetCtx(), m.getLink(true), m.tables, conditionStr, conditionArgs...)
}

View File

@ -8,7 +8,6 @@ package gdb
import (
"database/sql"
"fmt"
"github.com/gogf/gf/container/gset"
"reflect"
@ -211,7 +210,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err
}
}()
if m.data == nil {
return nil, gerror.New("inserting into table with empty data")
return nil, gerror.NewCode(gerror.CodeMissingParameter, "inserting into table with empty data")
}
var (
list List
@ -276,12 +275,12 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err
}
default:
return result, gerror.New(fmt.Sprint("unsupported list type:", kind))
return result, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported list type:%v", kind)
}
}
if len(list) < 1 {
return result, gerror.New("data list cannot be empty")
return result, gerror.NewCode(gerror.CodeMissingParameter, "data list cannot be empty")
}
// Automatic handling for creating/updating time.
@ -366,7 +365,11 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op
}
default:
return option, gerror.Newf(`unsupported OnDuplicate parameter type "%s"`, reflect.TypeOf(m.onDuplicate))
return option, gerror.NewCodef(
gerror.CodeInvalidParameter,
`unsupported OnDuplicate parameter type "%s"`,
reflect.TypeOf(m.onDuplicate),
)
}
}
} else if onDuplicateExKeySet.Size() > 0 {
@ -406,7 +409,11 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er
return gconv.Strings(onDuplicateEx), nil
default:
return nil, gerror.Newf(`unsupported OnDuplicateEx parameter type "%s"`, reflect.TypeOf(onDuplicateEx))
return nil, gerror.NewCodef(
gerror.CodeInvalidParameter,
`unsupported OnDuplicateEx parameter type "%s"`,
reflect.TypeOf(onDuplicateEx),
)
}
}

View File

@ -316,7 +316,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
reflectKind = reflectValue.Kind()
if reflectKind != reflect.Ptr {
return gerror.New(`the parameter "pointer" for function Scan should type of pointer`)
return gerror.NewCode(gerror.CodeInvalidParameter, `the parameter "pointer" for function Scan should type of pointer`)
}
for reflectKind == reflect.Ptr {
reflectValue = reflectValue.Elem()
@ -331,7 +331,10 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
return m.doStruct(pointer, where...)
default:
return gerror.New(`element of parameter "pointer" for function Scan should type of struct/*struct/[]struct/[]*struct`)
return gerror.NewCode(
gerror.CodeInvalidParameter,
`element of parameter "pointer" for function Scan should type of struct/*struct/[]struct/[]*struct`,
)
}
}

View File

@ -39,7 +39,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro
}
}()
if m.data == nil {
return nil, gerror.New("updating table with empty data")
return nil, gerror.NewCode(gerror.CodeMissingParameter, "updating table with empty data")
}
var (
updateData = m.data
@ -80,7 +80,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro
}
conditionStr := conditionWhere + conditionExtra
if !gstr.ContainsI(conditionStr, " WHERE ") {
return nil, gerror.New("there should be WHERE condition statement for UPDATE operation")
return nil, gerror.NewCode(gerror.CodeMissingParameter, "there should be WHERE condition statement for UPDATE operation")
}
return m.db.DoUpdate(
m.GetCtx(),

View File

@ -126,7 +126,8 @@ func (m *Model) doWithScanStruct(pointer interface{}) error {
}
}
if relatedFieldValue == nil {
return gerror.Newf(
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`cannot find the related value for attribute name "%s" of with tag "%s"`,
relatedAttrName, withTag,
)
@ -238,7 +239,8 @@ func (m *Model) doWithScanStructs(pointer interface{}) error {
}
}
if relatedFieldValue == nil {
return gerror.Newf(
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`cannot find the related value for attribute name "%s" of with tag "%s"`,
relatedAttrName, withTag,
)

View File

@ -59,7 +59,7 @@ func (s *Stmt) doStmtCommit(ctx context.Context, stmtType string, args ...interf
result = s.Stmt.QueryRowContext(ctx, args...)
default:
panic(gerror.Newf(`invalid stmtType: %s`, stmtType))
panic(gerror.NewCodef(gerror.CodeInvalidParameter, `invalid stmtType: %s`, stmtType))
}
var (
timestampMilli2 = gtime.TimestampMilli()

View File

@ -55,7 +55,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
// Necessary checks for parameters.
if bindToAttrName == "" {
return gerror.New(`bindToAttrName should not be empty`)
return gerror.NewCode(gerror.CodeInvalidParameter, `bindToAttrName should not be empty`)
}
var (
@ -67,12 +67,12 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
reflectKind = reflectValue.Kind()
}
if reflectKind != reflect.Ptr {
return gerror.Newf("listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind)
return gerror.NewCodef(gerror.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.Newf("listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind)
return gerror.NewCodef(gerror.CodeInvalidParameter, "listPointer should be type of *[]struct/*[]*struct, but got: %v", reflectKind)
}
length := len(result)
if length == 0 {
@ -135,7 +135,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
relationResultFieldName = array[0]
relationBindToSubAttrName = array[1]
if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationResultFieldName); key == "" {
return gerror.Newf(
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`cannot find possible related table field name "%s" from given relation key "%s"`,
relationResultFieldName,
relationKVStr,
@ -144,14 +145,14 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
relationResultFieldName = key
}
} else {
return gerror.New(`parameter relationKV should be format of "ResultFieldName:BindToAttrName"`)
return gerror.NewCode(gerror.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.Newf(`cannot find the relation data map, maybe invalid relation given "%v"`, relationKV)
return gerror.NewCodef(gerror.CodeInvalidParameter, `cannot find the relation data map, maybe invalid relation given "%v"`, relationKV)
}
}
// Bind to target attribute.
@ -164,11 +165,19 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
)
if arrayItemType.Kind() == reflect.Ptr {
if bindToAttrField, ok = arrayItemType.Elem().FieldByName(bindToAttrName); !ok {
return gerror.Newf(`invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, bindToAttrName)
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`,
bindToAttrName,
)
}
} else {
if bindToAttrField, ok = arrayItemType.FieldByName(bindToAttrName); !ok {
return gerror.Newf(`invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, bindToAttrName)
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`,
bindToAttrName,
)
}
}
bindToAttrType = bindToAttrField.Type
@ -210,7 +219,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
relationFromAttrValue = arrayElemValue
}
if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() {
return gerror.Newf(`invalid relation specified: "%v"`, relationKV)
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
}
// Check and find possible bind to attribute name.
if relationKVStr != "" && !relationBindToSubAttrNameChecked {
@ -224,7 +233,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
filedMap[relationFromAttrType.Field(i).Name] = struct{}{}
}
if key, _ := gutil.MapPossibleItemByKey(filedMap, relationBindToSubAttrName); key == "" {
return gerror.Newf(
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`cannot find possible related attribute name "%s" from given relation key "%s"`,
relationBindToSubAttrName,
relationKVStr,
@ -255,10 +265,14 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
} else {
// May be the attribute does not exist yet.
return gerror.Newf(`invalid relation specified: "%v"`, relationKV)
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
}
} else {
return gerror.Newf(`relationKey should not be empty as field "%s" is slice`, bindToAttrName)
return gerror.NewCodef(
gerror.CodeInvalidParameter,
`relationKey should not be empty as field "%s" is slice`,
bindToAttrName,
)
}
case reflect.Ptr:
@ -287,7 +301,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
} else {
// May be the attribute does not exist yet.
return gerror.Newf(`invalid relation specified: "%v"`, relationKV)
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
}
} else {
if i >= len(result) {
@ -331,7 +345,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
} else {
// May be the attribute does not exist yet.
return gerror.Newf(`invalid relation specified: "%v"`, relationKV)
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
}
} else {
if i >= len(result) {
@ -355,7 +369,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
default:
return gerror.Newf(`unsupported attribute type: %s`, bindToAttrKind.String())
return gerror.NewCodef(gerror.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String())
}
}
reflect.ValueOf(listPointer).Elem().Set(arrayValue)

View File

@ -408,7 +408,7 @@ func (user *User) UnmarshalValue(value interface{}) error {
}
return nil
}
return gerror.Newf(`unsupported value type for UnmarshalValue: %v`, reflect.TypeOf(value))
return gerror.NewCodef(gerror.CodeInvalidParameter, `unsupported value type for UnmarshalValue: %v`, reflect.TypeOf(value))
}
func Test_Model_Scan_UnmarshalValue(t *testing.T) {

View File

@ -114,7 +114,7 @@ func ConfigFromStr(str string) (config *Config, err error) {
config.Port = DefaultRedisPort
}
} else {
err = gerror.Newf(`invalid redis configuration: "%s"`, str)
err = gerror.NewCodef(gerror.CodeInvalidConfiguration, `invalid redis configuration: "%s"`, str)
}
return
}

View File

@ -50,7 +50,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.New(`current connection does not support "ConnWithTimeout"`)
return gvar.New(nil), gerror.NewCode(gerror.CodeNotSupported, `current connection does not support "ConnWithTimeout"`)
}
return conn.DoWithTimeout(timeout, commandName, args...)
}
@ -107,7 +107,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.New(`current connection does not support "ConnWithTimeout"`)
return gvar.New(nil), gerror.NewCode(gerror.CodeNotSupported, `current connection does not support "ConnWithTimeout"`)
}
return resultToVar(conn.ReceiveWithTimeout(timeout))
}