mirror of
https://gitee.com/johng/gf.git
synced 2024-12-01 19:57:40 +08:00
add error code for components
This commit is contained in:
parent
f72d991c36
commit
0ddacdd7e2
@ -123,7 +123,7 @@ func (a *Array) Set(index int, value interface{}) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
a.array[index] = value
|
a.array[index] = value
|
||||||
return nil
|
return nil
|
||||||
@ -176,7 +176,7 @@ func (a *Array) InsertBefore(index int, value interface{}) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]interface{}{}, a.array[index:]...)
|
rear := append([]interface{}{}, a.array[index:]...)
|
||||||
a.array = append(a.array[0:index], value)
|
a.array = append(a.array[0:index], value)
|
||||||
@ -189,7 +189,7 @@ func (a *Array) InsertAfter(index int, value interface{}) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]interface{}{}, a.array[index+1:]...)
|
rear := append([]interface{}{}, a.array[index+1:]...)
|
||||||
a.array = append(a.array[0:index+1], value)
|
a.array = append(a.array[0:index+1], value)
|
||||||
@ -545,7 +545,7 @@ func (a *Array) Fill(startIndex int, num int, value interface{}) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if startIndex < 0 || startIndex > len(a.array) {
|
if startIndex < 0 || startIndex > len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", startIndex, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||||
}
|
}
|
||||||
for i := startIndex; i < startIndex+num; i++ {
|
for i := startIndex; i < startIndex+num; i++ {
|
||||||
if i > len(a.array)-1 {
|
if i > len(a.array)-1 {
|
||||||
|
@ -104,7 +104,7 @@ func (a *IntArray) Set(index int, value int) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
a.array[index] = value
|
a.array[index] = value
|
||||||
return nil
|
return nil
|
||||||
@ -175,7 +175,7 @@ func (a *IntArray) InsertBefore(index int, value int) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]int{}, a.array[index:]...)
|
rear := append([]int{}, a.array[index:]...)
|
||||||
a.array = append(a.array[0:index], value)
|
a.array = append(a.array[0:index], value)
|
||||||
@ -188,7 +188,7 @@ func (a *IntArray) InsertAfter(index int, value int) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]int{}, a.array[index+1:]...)
|
rear := append([]int{}, a.array[index+1:]...)
|
||||||
a.array = append(a.array[0:index+1], value)
|
a.array = append(a.array[0:index+1], value)
|
||||||
@ -559,7 +559,7 @@ func (a *IntArray) Fill(startIndex int, num int, value int) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if startIndex < 0 || startIndex > len(a.array) {
|
if startIndex < 0 || startIndex > len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", startIndex, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||||
}
|
}
|
||||||
for i := startIndex; i < startIndex+num; i++ {
|
for i := startIndex; i < startIndex+num; i++ {
|
||||||
if i > len(a.array)-1 {
|
if i > len(a.array)-1 {
|
||||||
|
@ -90,7 +90,7 @@ func (a *StrArray) Set(index int, value string) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
a.array[index] = value
|
a.array[index] = value
|
||||||
return nil
|
return nil
|
||||||
@ -162,7 +162,7 @@ func (a *StrArray) InsertBefore(index int, value string) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]string{}, a.array[index:]...)
|
rear := append([]string{}, a.array[index:]...)
|
||||||
a.array = append(a.array[0:index], value)
|
a.array = append(a.array[0:index], value)
|
||||||
@ -175,7 +175,7 @@ func (a *StrArray) InsertAfter(index int, value string) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if index < 0 || index >= len(a.array) {
|
if index < 0 || index >= len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", index, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||||
}
|
}
|
||||||
rear := append([]string{}, a.array[index+1:]...)
|
rear := append([]string{}, a.array[index+1:]...)
|
||||||
a.array = append(a.array[0:index+1], value)
|
a.array = append(a.array[0:index+1], value)
|
||||||
@ -562,7 +562,7 @@ func (a *StrArray) Fill(startIndex int, num int, value string) error {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if startIndex < 0 || startIndex > len(a.array) {
|
if startIndex < 0 || startIndex > len(a.array) {
|
||||||
return gerror.Newf("index %d out of array range %d", startIndex, len(a.array))
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||||
}
|
}
|
||||||
for i := startIndex; i < startIndex+num; i++ {
|
for i := startIndex; i < startIndex+num; i++ {
|
||||||
if i > len(a.array)-1 {
|
if i > len(a.array)-1 {
|
||||||
|
@ -66,7 +66,7 @@ func New(ttl time.Duration, newFunc NewFunc, expireFunc ...ExpireFunc) *Pool {
|
|||||||
// Put puts an item to pool.
|
// Put puts an item to pool.
|
||||||
func (p *Pool) Put(value interface{}) error {
|
func (p *Pool) Put(value interface{}) error {
|
||||||
if p.closed.Val() {
|
if p.closed.Val() {
|
||||||
return gerror.New("pool is closed")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "pool is closed")
|
||||||
}
|
}
|
||||||
item := &poolItem{
|
item := &poolItem{
|
||||||
value: value,
|
value: value,
|
||||||
@ -117,7 +117,7 @@ func (p *Pool) Get() (interface{}, error) {
|
|||||||
if p.NewFunc != nil {
|
if p.NewFunc != nil {
|
||||||
return p.NewFunc()
|
return p.NewFunc()
|
||||||
}
|
}
|
||||||
return nil, gerror.New("pool is empty")
|
return nil, gerror.NewCode(gerror.CodeInvalidOperation, "pool is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size returns the count of available items of pool.
|
// Size returns the count of available items of pool.
|
||||||
|
@ -63,7 +63,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv ...[]byte) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
blockSize := block.BlockSize()
|
blockSize := block.BlockSize()
|
||||||
if len(cipherText) < blockSize {
|
if len(cipherText) < blockSize {
|
||||||
return nil, gerror.New("cipherText too short")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText too short")
|
||||||
}
|
}
|
||||||
ivValue := ([]byte)(nil)
|
ivValue := ([]byte)(nil)
|
||||||
if len(iv) > 0 {
|
if len(iv) > 0 {
|
||||||
@ -72,7 +72,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv ...[]byte) ([]byte, error) {
|
|||||||
ivValue = []byte(IVDefaultValue)
|
ivValue = []byte(IVDefaultValue)
|
||||||
}
|
}
|
||||||
if len(cipherText)%blockSize != 0 {
|
if len(cipherText)%blockSize != 0 {
|
||||||
return nil, gerror.New("cipherText is not a multiple of the block size")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText is not a multiple of the block size")
|
||||||
}
|
}
|
||||||
blockModel := cipher.NewCBCDecrypter(block, ivValue)
|
blockModel := cipher.NewCBCDecrypter(block, ivValue)
|
||||||
plainText := make([]byte, len(cipherText))
|
plainText := make([]byte, len(cipherText))
|
||||||
@ -93,22 +93,22 @@ func PKCS5Padding(src []byte, blockSize int) []byte {
|
|||||||
func PKCS5UnPadding(src []byte, blockSize int) ([]byte, error) {
|
func PKCS5UnPadding(src []byte, blockSize int) ([]byte, error) {
|
||||||
length := len(src)
|
length := len(src)
|
||||||
if blockSize <= 0 {
|
if blockSize <= 0 {
|
||||||
return nil, gerror.New("invalid blocklen")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid blocklen")
|
||||||
}
|
}
|
||||||
|
|
||||||
if length%blockSize != 0 || length == 0 {
|
if length%blockSize != 0 || length == 0 {
|
||||||
return nil, gerror.New("invalid data len")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid data len")
|
||||||
}
|
}
|
||||||
|
|
||||||
unpadding := int(src[length-1])
|
unpadding := int(src[length-1])
|
||||||
if unpadding > blockSize || unpadding == 0 {
|
if unpadding > blockSize || unpadding == 0 {
|
||||||
return nil, gerror.New("invalid padding")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid padding")
|
||||||
}
|
}
|
||||||
|
|
||||||
padding := src[length-unpadding:]
|
padding := src[length-unpadding:]
|
||||||
for i := 0; i < unpadding; i++ {
|
for i := 0; i < unpadding; i++ {
|
||||||
if padding[i] != byte(unpadding) {
|
if padding[i] != byte(unpadding) {
|
||||||
return nil, gerror.New("invalid padding")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "invalid padding")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,7 +146,7 @@ func DecryptCFB(cipherText []byte, key []byte, unPadding int, iv ...[]byte) ([]b
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if len(cipherText) < aes.BlockSize {
|
if len(cipherText) < aes.BlockSize {
|
||||||
return nil, gerror.New("cipherText too short")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "cipherText too short")
|
||||||
}
|
}
|
||||||
ivValue := ([]byte)(nil)
|
ivValue := ([]byte)(nil)
|
||||||
if len(iv) > 0 {
|
if len(iv) > 0 {
|
||||||
|
@ -66,7 +66,7 @@ func DecryptECB(cipherText []byte, key []byte, padding int) ([]byte, error) {
|
|||||||
// The length of the <key> should be either 16 or 24 bytes.
|
// The length of the <key> should be either 16 or 24 bytes.
|
||||||
func EncryptECBTriple(plainText []byte, key []byte, padding int) ([]byte, error) {
|
func EncryptECBTriple(plainText []byte, key []byte, padding int) ([]byte, error) {
|
||||||
if len(key) != 16 && len(key) != 24 {
|
if len(key) != 16 && len(key) != 24 {
|
||||||
return nil, gerror.New("key length error")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length error")
|
||||||
}
|
}
|
||||||
|
|
||||||
text, err := Padding(plainText, padding)
|
text, err := Padding(plainText, padding)
|
||||||
@ -100,7 +100,7 @@ func EncryptECBTriple(plainText []byte, key []byte, padding int) ([]byte, error)
|
|||||||
// The length of the <key> should be either 16 or 24 bytes.
|
// The length of the <key> should be either 16 or 24 bytes.
|
||||||
func DecryptECBTriple(cipherText []byte, key []byte, padding int) ([]byte, error) {
|
func DecryptECBTriple(cipherText []byte, key []byte, padding int) ([]byte, error) {
|
||||||
if len(key) != 16 && len(key) != 24 {
|
if len(key) != 16 && len(key) != 24 {
|
||||||
return nil, gerror.New("key length error")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length error")
|
||||||
}
|
}
|
||||||
|
|
||||||
var newKey []byte
|
var newKey []byte
|
||||||
@ -138,7 +138,7 @@ func EncryptCBC(plainText []byte, key []byte, iv []byte, padding int) ([]byte, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(iv) != block.BlockSize() {
|
if len(iv) != block.BlockSize() {
|
||||||
return nil, gerror.New("iv length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
text, err := Padding(plainText, padding)
|
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() {
|
if len(iv) != block.BlockSize() {
|
||||||
return nil, gerror.New("iv length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
text := make([]byte, len(cipherText))
|
text := make([]byte, len(cipherText))
|
||||||
@ -179,7 +179,7 @@ func DecryptCBC(cipherText []byte, key []byte, iv []byte, padding int) ([]byte,
|
|||||||
// EncryptCBCTriple encrypts <plainText> using TripleDES and CBC mode.
|
// EncryptCBCTriple encrypts <plainText> using TripleDES and CBC mode.
|
||||||
func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]byte, error) {
|
func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]byte, error) {
|
||||||
if len(key) != 16 && len(key) != 24 {
|
if len(key) != 16 && len(key) != 24 {
|
||||||
return nil, gerror.New("key length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
var newKey []byte
|
var newKey []byte
|
||||||
@ -196,7 +196,7 @@ func EncryptCBCTriple(plainText []byte, key []byte, iv []byte, padding int) ([]b
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(iv) != block.BlockSize() {
|
if len(iv) != block.BlockSize() {
|
||||||
return nil, gerror.New("iv length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
text, err := Padding(plainText, padding)
|
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.
|
// DecryptCBCTriple decrypts <cipherText> using TripleDES and CBC mode.
|
||||||
func DecryptCBCTriple(cipherText []byte, key []byte, iv []byte, padding int) ([]byte, error) {
|
func DecryptCBCTriple(cipherText []byte, key []byte, iv []byte, padding int) ([]byte, error) {
|
||||||
if len(key) != 16 && len(key) != 24 {
|
if len(key) != 16 && len(key) != 24 {
|
||||||
return nil, gerror.New("key length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "key length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
var newKey []byte
|
var newKey []byte
|
||||||
@ -231,7 +231,7 @@ func DecryptCBCTriple(cipherText []byte, key []byte, iv []byte, padding int) ([]
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(iv) != block.BlockSize() {
|
if len(iv) != block.BlockSize() {
|
||||||
return nil, gerror.New("iv length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "iv length invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
text := make([]byte, len(cipherText))
|
text := make([]byte, len(cipherText))
|
||||||
@ -262,12 +262,12 @@ func Padding(text []byte, padding int) ([]byte, error) {
|
|||||||
switch padding {
|
switch padding {
|
||||||
case NOPADDING:
|
case NOPADDING:
|
||||||
if len(text)%8 != 0 {
|
if len(text)%8 != 0 {
|
||||||
return nil, gerror.New("text length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "text length invalid")
|
||||||
}
|
}
|
||||||
case PKCS5PADDING:
|
case PKCS5PADDING:
|
||||||
return PaddingPKCS5(text, 8), nil
|
return PaddingPKCS5(text, 8), nil
|
||||||
default:
|
default:
|
||||||
return nil, gerror.New("padding type error")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "padding type error")
|
||||||
}
|
}
|
||||||
|
|
||||||
return text, nil
|
return text, nil
|
||||||
@ -277,12 +277,12 @@ func UnPadding(text []byte, padding int) ([]byte, error) {
|
|||||||
switch padding {
|
switch padding {
|
||||||
case NOPADDING:
|
case NOPADDING:
|
||||||
if len(text)%8 != 0 {
|
if len(text)%8 != 0 {
|
||||||
return nil, gerror.New("text length invalid")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "text length invalid")
|
||||||
}
|
}
|
||||||
case PKCS5PADDING:
|
case PKCS5PADDING:
|
||||||
return UnPaddingPKCS5(text), nil
|
return UnPaddingPKCS5(text), nil
|
||||||
default:
|
default:
|
||||||
return nil, gerror.New("padding type error")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "padding type error")
|
||||||
}
|
}
|
||||||
return text, nil
|
return text, nil
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,6 @@ package gdb
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gogf/gf/errors/gerror"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
@ -333,7 +332,10 @@ func New(group ...string) (db DB, err error) {
|
|||||||
defer configs.RUnlock()
|
defer configs.RUnlock()
|
||||||
|
|
||||||
if len(configs.config) < 1 {
|
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 _, ok := configs.config[groupName]; ok {
|
||||||
if node, err := getConfigNodeByGroup(groupName, true); err == nil {
|
if node, err := getConfigNodeByGroup(groupName, true); err == nil {
|
||||||
@ -352,7 +354,8 @@ func New(group ...string) (db DB, err error) {
|
|||||||
}
|
}
|
||||||
return c.db, nil
|
return c.db, nil
|
||||||
} else {
|
} 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?`,
|
`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,
|
node.Type, node.Type,
|
||||||
)
|
)
|
||||||
@ -361,7 +364,8 @@ func New(group ...string) (db DB, err error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} 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?`,
|
`database configuration node "%s" is not found, did you misspell group name "%s" or miss the database configuration?`,
|
||||||
groupName, groupName,
|
groupName, groupName,
|
||||||
)
|
)
|
||||||
@ -404,7 +408,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(masterList) < 1 {
|
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 {
|
if len(slaveList) < 1 {
|
||||||
slaveList = masterList
|
slaveList = masterList
|
||||||
@ -415,7 +419,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) {
|
|||||||
return getConfigNodeByWeight(slaveList), nil
|
return getConfigNodeByWeight(slaveList), nil
|
||||||
}
|
}
|
||||||
} else {
|
} 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -89,7 +89,7 @@ func (c *Core) GetCtxTimeout(timeoutType int, ctx context.Context) (context.Cont
|
|||||||
return context.WithTimeout(ctx, c.db.GetConfig().PrepareTimeout)
|
return context.WithTimeout(ctx, c.db.GetConfig().PrepareTimeout)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
panic(gerror.Newf("invalid context timeout type: %d", timeoutType))
|
panic(gerror.NewCodef(gerror.CodeInvalidParameter, "invalid context timeout type: %d", timeoutType))
|
||||||
}
|
}
|
||||||
return ctx, func() {}
|
return ctx, func() {}
|
||||||
}
|
}
|
||||||
@ -553,7 +553,7 @@ func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data inter
|
|||||||
updates = gconv.String(data)
|
updates = gconv.String(data)
|
||||||
}
|
}
|
||||||
if len(updates) == 0 {
|
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 {
|
if len(params) > 0 {
|
||||||
args = append(params, args...)
|
args = append(params, args...)
|
||||||
|
@ -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) {
|
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 c.db.GetConfig().CtxStrict {
|
||||||
if v := ctx.Value(ctxStrictKeyName); v == nil {
|
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
|
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 c.db.GetConfig().CtxStrict {
|
||||||
if v := ctx.Value(ctxStrictKeyName); v == nil {
|
if v := ctx.Value(ctxStrictKeyName); v == nil {
|
||||||
return nil, gerror.New(ctxStrictErrorStr)
|
return nil, gerror.NewCode(gerror.CodeMissingParameter, ctxStrictErrorStr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -214,7 +214,7 @@ func (d *DriverMssql) TableFields(ctx context.Context, table string, schema ...s
|
|||||||
charL, charR := d.GetChars()
|
charL, charR := d.GetChars()
|
||||||
table = gstr.Trim(table, charL+charR)
|
table = gstr.Trim(table, charL+charR)
|
||||||
if gstr.Contains(table, " ") {
|
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()
|
useSchema := d.db.GetSchema()
|
||||||
if len(schema) > 0 && schema[0] != "" {
|
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) {
|
func (d *DriverMssql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) {
|
||||||
switch option.InsertOption {
|
switch option.InsertOption {
|
||||||
case insertOptionSave:
|
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:
|
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:
|
default:
|
||||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||||
|
@ -121,7 +121,7 @@ func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...s
|
|||||||
charL, charR := d.GetChars()
|
charL, charR := d.GetChars()
|
||||||
table = gstr.Trim(table, charL+charR)
|
table = gstr.Trim(table, charL+charR)
|
||||||
if gstr.Contains(table, " ") {
|
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()
|
useSchema := d.schema.Val()
|
||||||
if len(schema) > 0 && schema[0] != "" {
|
if len(schema) > 0 && schema[0] != "" {
|
||||||
|
@ -186,7 +186,7 @@ func (d *DriverOracle) TableFields(ctx context.Context, table string, schema ...
|
|||||||
charL, charR := d.GetChars()
|
charL, charR := d.GetChars()
|
||||||
table = gstr.Trim(table, charL+charR)
|
table = gstr.Trim(table, charL+charR)
|
||||||
if gstr.Contains(table, " ") {
|
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()
|
useSchema := d.db.GetSchema()
|
||||||
if len(schema) > 0 && schema[0] != "" {
|
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) {
|
func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) {
|
||||||
switch option.InsertOption {
|
switch option.InsertOption {
|
||||||
case insertOptionSave:
|
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:
|
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 (
|
var (
|
||||||
|
@ -126,7 +126,7 @@ func (d *DriverPgsql) TableFields(ctx context.Context, table string, schema ...s
|
|||||||
charL, charR := d.GetChars()
|
charL, charR := d.GetChars()
|
||||||
table = gstr.Trim(table, charL+charR)
|
table = gstr.Trim(table, charL+charR)
|
||||||
if gstr.Contains(table, " ") {
|
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)
|
table, _ = gregex.ReplaceString("\"", "", table)
|
||||||
useSchema := d.db.GetSchema()
|
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) {
|
func (d *DriverPgsql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) {
|
||||||
switch option.InsertOption {
|
switch option.InsertOption {
|
||||||
case insertOptionSave:
|
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:
|
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:
|
default:
|
||||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||||
|
@ -99,7 +99,7 @@ func (d *DriverSqlite) TableFields(ctx context.Context, table string, schema ...
|
|||||||
charL, charR := d.GetChars()
|
charL, charR := d.GetChars()
|
||||||
table = gstr.Trim(table, charL+charR)
|
table = gstr.Trim(table, charL+charR)
|
||||||
if gstr.Contains(table, " ") {
|
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()
|
useSchema := d.db.GetSchema()
|
||||||
if len(schema) > 0 && schema[0] != "" {
|
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) {
|
func (d *DriverSqlite) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) {
|
||||||
switch option.InsertOption {
|
switch option.InsertOption {
|
||||||
case insertOptionSave:
|
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:
|
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:
|
default:
|
||||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||||
|
@ -805,7 +805,7 @@ func handleArguments(sql string, args []interface{}) (newSql string, newArgs []i
|
|||||||
// formatError customizes and returns the SQL error.
|
// formatError customizes and returns the SQL error.
|
||||||
func formatError(err error, sql string, args ...interface{}) error {
|
func formatError(err error, sql string, args ...interface{}) error {
|
||||||
if err != nil && err != ErrNoRows {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
|
|||||||
}
|
}
|
||||||
conditionStr := conditionWhere + conditionExtra
|
conditionStr := conditionWhere + conditionExtra
|
||||||
if !gstr.ContainsI(conditionStr, " WHERE ") {
|
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...)
|
return m.db.DoDelete(m.GetCtx(), m.getLink(true), m.tables, conditionStr, conditionArgs...)
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,6 @@ package gdb
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
|
||||||
"github.com/gogf/gf/container/gset"
|
"github.com/gogf/gf/container/gset"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
@ -211,7 +210,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if m.data == nil {
|
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 (
|
var (
|
||||||
list List
|
list List
|
||||||
@ -276,12 +275,12 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
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 {
|
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.
|
// Automatic handling for creating/updating time.
|
||||||
@ -366,7 +365,11 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
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 {
|
} else if onDuplicateExKeySet.Size() > 0 {
|
||||||
@ -406,7 +409,11 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er
|
|||||||
return gconv.Strings(onDuplicateEx), nil
|
return gconv.Strings(onDuplicateEx), nil
|
||||||
|
|
||||||
default:
|
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),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -316,7 +316,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
|
|||||||
|
|
||||||
reflectKind = reflectValue.Kind()
|
reflectKind = reflectValue.Kind()
|
||||||
if reflectKind != reflect.Ptr {
|
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 {
|
for reflectKind == reflect.Ptr {
|
||||||
reflectValue = reflectValue.Elem()
|
reflectValue = reflectValue.Elem()
|
||||||
@ -331,7 +331,10 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
|
|||||||
return m.doStruct(pointer, where...)
|
return m.doStruct(pointer, where...)
|
||||||
|
|
||||||
default:
|
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`,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,7 +39,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if m.data == nil {
|
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 (
|
var (
|
||||||
updateData = m.data
|
updateData = m.data
|
||||||
@ -80,7 +80,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro
|
|||||||
}
|
}
|
||||||
conditionStr := conditionWhere + conditionExtra
|
conditionStr := conditionWhere + conditionExtra
|
||||||
if !gstr.ContainsI(conditionStr, " WHERE ") {
|
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(
|
return m.db.DoUpdate(
|
||||||
m.GetCtx(),
|
m.GetCtx(),
|
||||||
|
@ -126,7 +126,8 @@ func (m *Model) doWithScanStruct(pointer interface{}) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if relatedFieldValue == nil {
|
if relatedFieldValue == nil {
|
||||||
return gerror.Newf(
|
return gerror.NewCodef(
|
||||||
|
gerror.CodeInvalidParameter,
|
||||||
`cannot find the related value for attribute name "%s" of with tag "%s"`,
|
`cannot find the related value for attribute name "%s" of with tag "%s"`,
|
||||||
relatedAttrName, withTag,
|
relatedAttrName, withTag,
|
||||||
)
|
)
|
||||||
@ -238,7 +239,8 @@ func (m *Model) doWithScanStructs(pointer interface{}) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if relatedFieldValue == nil {
|
if relatedFieldValue == nil {
|
||||||
return gerror.Newf(
|
return gerror.NewCodef(
|
||||||
|
gerror.CodeInvalidParameter,
|
||||||
`cannot find the related value for attribute name "%s" of with tag "%s"`,
|
`cannot find the related value for attribute name "%s" of with tag "%s"`,
|
||||||
relatedAttrName, withTag,
|
relatedAttrName, withTag,
|
||||||
)
|
)
|
||||||
|
@ -59,7 +59,7 @@ func (s *Stmt) doStmtCommit(ctx context.Context, stmtType string, args ...interf
|
|||||||
result = s.Stmt.QueryRowContext(ctx, args...)
|
result = s.Stmt.QueryRowContext(ctx, args...)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
panic(gerror.Newf(`invalid stmtType: %s`, stmtType))
|
panic(gerror.NewCodef(gerror.CodeInvalidParameter, `invalid stmtType: %s`, stmtType))
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
timestampMilli2 = gtime.TimestampMilli()
|
timestampMilli2 = gtime.TimestampMilli()
|
||||||
|
@ -55,7 +55,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
}
|
}
|
||||||
// Necessary checks for parameters.
|
// Necessary checks for parameters.
|
||||||
if bindToAttrName == "" {
|
if bindToAttrName == "" {
|
||||||
return gerror.New(`bindToAttrName should not be empty`)
|
return gerror.NewCode(gerror.CodeInvalidParameter, `bindToAttrName should not be empty`)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -67,12 +67,12 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
reflectKind = reflectValue.Kind()
|
reflectKind = reflectValue.Kind()
|
||||||
}
|
}
|
||||||
if reflectKind != reflect.Ptr {
|
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()
|
reflectValue = reflectValue.Elem()
|
||||||
reflectKind = reflectValue.Kind()
|
reflectKind = reflectValue.Kind()
|
||||||
if reflectKind != reflect.Slice && reflectKind != reflect.Array {
|
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)
|
length := len(result)
|
||||||
if length == 0 {
|
if length == 0 {
|
||||||
@ -135,7 +135,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
relationResultFieldName = array[0]
|
relationResultFieldName = array[0]
|
||||||
relationBindToSubAttrName = array[1]
|
relationBindToSubAttrName = array[1]
|
||||||
if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationResultFieldName); key == "" {
|
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"`,
|
`cannot find possible related table field name "%s" from given relation key "%s"`,
|
||||||
relationResultFieldName,
|
relationResultFieldName,
|
||||||
relationKVStr,
|
relationKVStr,
|
||||||
@ -144,14 +145,14 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
relationResultFieldName = key
|
relationResultFieldName = key
|
||||||
}
|
}
|
||||||
} else {
|
} 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 != "" {
|
if relationResultFieldName != "" {
|
||||||
// Note that the value might be type of slice.
|
// Note that the value might be type of slice.
|
||||||
relationDataMap = result.MapKeyValue(relationResultFieldName)
|
relationDataMap = result.MapKeyValue(relationResultFieldName)
|
||||||
}
|
}
|
||||||
if len(relationDataMap) == 0 {
|
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.
|
// Bind to target attribute.
|
||||||
@ -164,11 +165,19 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
)
|
)
|
||||||
if arrayItemType.Kind() == reflect.Ptr {
|
if arrayItemType.Kind() == reflect.Ptr {
|
||||||
if bindToAttrField, ok = arrayItemType.Elem().FieldByName(bindToAttrName); !ok {
|
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 {
|
} else {
|
||||||
if bindToAttrField, ok = arrayItemType.FieldByName(bindToAttrName); !ok {
|
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
|
bindToAttrType = bindToAttrField.Type
|
||||||
@ -210,7 +219,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
relationFromAttrValue = arrayElemValue
|
relationFromAttrValue = arrayElemValue
|
||||||
}
|
}
|
||||||
if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() {
|
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.
|
// Check and find possible bind to attribute name.
|
||||||
if relationKVStr != "" && !relationBindToSubAttrNameChecked {
|
if relationKVStr != "" && !relationBindToSubAttrNameChecked {
|
||||||
@ -224,7 +233,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
filedMap[relationFromAttrType.Field(i).Name] = struct{}{}
|
filedMap[relationFromAttrType.Field(i).Name] = struct{}{}
|
||||||
}
|
}
|
||||||
if key, _ := gutil.MapPossibleItemByKey(filedMap, relationBindToSubAttrName); key == "" {
|
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"`,
|
`cannot find possible related attribute name "%s" from given relation key "%s"`,
|
||||||
relationBindToSubAttrName,
|
relationBindToSubAttrName,
|
||||||
relationKVStr,
|
relationKVStr,
|
||||||
@ -255,10 +265,14 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// May be the attribute does not exist yet.
|
// 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 {
|
} 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:
|
case reflect.Ptr:
|
||||||
@ -287,7 +301,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// May be the attribute does not exist yet.
|
// 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 {
|
} else {
|
||||||
if i >= len(result) {
|
if i >= len(result) {
|
||||||
@ -331,7 +345,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// May be the attribute does not exist yet.
|
// 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 {
|
} else {
|
||||||
if i >= len(result) {
|
if i >= len(result) {
|
||||||
@ -355,7 +369,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
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)
|
reflect.ValueOf(listPointer).Elem().Set(arrayValue)
|
||||||
|
@ -408,7 +408,7 @@ func (user *User) UnmarshalValue(value interface{}) error {
|
|||||||
}
|
}
|
||||||
return nil
|
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) {
|
func Test_Model_Scan_UnmarshalValue(t *testing.T) {
|
||||||
|
@ -114,7 +114,7 @@ func ConfigFromStr(str string) (config *Config, err error) {
|
|||||||
config.Port = DefaultRedisPort
|
config.Port = DefaultRedisPort
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
err = gerror.Newf(`invalid redis configuration: "%s"`, str)
|
err = gerror.NewCodef(gerror.CodeInvalidConfiguration, `invalid redis configuration: "%s"`, str)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -50,7 +50,7 @@ func (c *Conn) do(timeout time.Duration, commandName string, args ...interface{}
|
|||||||
if timeout > 0 {
|
if timeout > 0 {
|
||||||
conn, ok := c.Conn.(redis.ConnWithTimeout)
|
conn, ok := c.Conn.(redis.ConnWithTimeout)
|
||||||
if !ok {
|
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...)
|
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) {
|
func (c *Conn) ReceiveVarWithTimeout(timeout time.Duration) (*gvar.Var, error) {
|
||||||
conn, ok := c.Conn.(redis.ConnWithTimeout)
|
conn, ok := c.Conn.(redis.ConnWithTimeout)
|
||||||
if !ok {
|
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))
|
return resultToVar(conn.ReceiveWithTimeout(timeout))
|
||||||
}
|
}
|
||||||
|
@ -59,11 +59,11 @@ func Convert(dstCharset string, srcCharset string, src string) (dst string, err
|
|||||||
transform.NewReader(bytes.NewReader([]byte(src)), e.NewDecoder()),
|
transform.NewReader(bytes.NewReader([]byte(src)), e.NewDecoder()),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", gerror.Newf("%s to utf8 failed. %v", srcCharset, err)
|
return "", gerror.WrapCodef(gerror.CodeInternalError, err, "%s to utf8 failed", srcCharset)
|
||||||
}
|
}
|
||||||
src = string(tmp)
|
src = string(tmp)
|
||||||
} else {
|
} else {
|
||||||
return dst, gerror.Newf("unsupport srcCharset: %s", srcCharset)
|
return dst, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported srcCharset: %s", srcCharset)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Do the converting from UTF-8 to <dstCharset>.
|
// Do the converting from UTF-8 to <dstCharset>.
|
||||||
@ -73,11 +73,11 @@ func Convert(dstCharset string, srcCharset string, src string) (dst string, err
|
|||||||
transform.NewReader(bytes.NewReader([]byte(src)), e.NewEncoder()),
|
transform.NewReader(bytes.NewReader([]byte(src)), e.NewEncoder()),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", gerror.Newf("utf to %s failed. %v", dstCharset, err)
|
return "", gerror.WrapCodef(gerror.CodeInternalError, err, "utf to %s failed", dstCharset)
|
||||||
}
|
}
|
||||||
dst = string(tmp)
|
dst = string(tmp)
|
||||||
} else {
|
} else {
|
||||||
return dst, gerror.Newf("unsupport dstCharset: %s", dstCharset)
|
return dst, gerror.NewCodef(gerror.CodeInvalidParameter, "unsupported dstCharset: %s", dstCharset)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
dst = src
|
dst = src
|
||||||
|
@ -70,7 +70,7 @@ func Decode(data []byte) (res map[string]interface{}, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if haveSection == false {
|
if haveSection == false {
|
||||||
return nil, gerror.New("failed to parse INI file, section not found")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "failed to parse INI file, section not found")
|
||||||
}
|
}
|
||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
@ -264,7 +264,7 @@ func doLoadContentWithOptions(dataType string, data []byte, options Options) (*J
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
err = gerror.New("unsupported type for loading")
|
err = gerror.NewCode(gerror.CodeInvalidParameter, "unsupported type for loading")
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -49,7 +49,7 @@ func New(text string) error {
|
|||||||
return &Error{
|
return &Error{
|
||||||
stack: callers(),
|
stack: callers(),
|
||||||
text: text,
|
text: text,
|
||||||
code: -1,
|
code: CodeNil,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,7 +58,7 @@ func Newf(format string, args ...interface{}) error {
|
|||||||
return &Error{
|
return &Error{
|
||||||
stack: callers(),
|
stack: callers(),
|
||||||
text: fmt.Sprintf(format, args...),
|
text: fmt.Sprintf(format, args...),
|
||||||
code: -1,
|
code: CodeNil,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,7 +68,7 @@ func NewSkip(skip int, text string) error {
|
|||||||
return &Error{
|
return &Error{
|
||||||
stack: callers(skip),
|
stack: callers(skip),
|
||||||
text: text,
|
text: text,
|
||||||
code: -1,
|
code: CodeNil,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,7 +78,7 @@ func NewSkipf(skip int, format string, args ...interface{}) error {
|
|||||||
return &Error{
|
return &Error{
|
||||||
stack: callers(skip),
|
stack: callers(skip),
|
||||||
text: fmt.Sprintf(format, args...),
|
text: fmt.Sprintf(format, args...),
|
||||||
code: -1,
|
code: CodeNil,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
25
errors/gerror/gerror_code.go
Normal file
25
errors/gerror/gerror_code.go
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
// 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 without error.
|
||||||
|
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.
|
||||||
|
)
|
@ -179,6 +179,9 @@ func (err *Error) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// formatSubStack formats the stack for error.
|
// formatSubStack formats the stack for error.
|
||||||
func formatSubStack(st stack, buffer *bytes.Buffer) {
|
func formatSubStack(st stack, buffer *bytes.Buffer) {
|
||||||
|
if st == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
index := 1
|
index := 1
|
||||||
space := " "
|
space := " "
|
||||||
for _, p := range st {
|
for _, p := range st {
|
||||||
|
28
errors/gerror/gerror_option.go
Normal file
28
errors/gerror/gerror_option.go
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
// 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
|
||||||
|
|
||||||
|
// Option is option for creating error.
|
||||||
|
type Option struct {
|
||||||
|
Error error // Wrapped error.
|
||||||
|
Stack bool // Record stack information into error.
|
||||||
|
Text string // Error text, which is created by New* functions.
|
||||||
|
Code int // Error code if necessary.
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOption creates and returns an error with Option.
|
||||||
|
func NewOption(option Option) error {
|
||||||
|
err := &Error{
|
||||||
|
error: option.Error,
|
||||||
|
text: option.Text,
|
||||||
|
code: option.Code,
|
||||||
|
}
|
||||||
|
if option.Stack {
|
||||||
|
err.stack = callers()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
@ -53,21 +53,24 @@ func Database(name ...string) gdb.DB {
|
|||||||
if configFilePath == "" {
|
if configFilePath == "" {
|
||||||
exampleFileName := "config.example.toml"
|
exampleFileName := "config.example.toml"
|
||||||
if exampleConfigFilePath, _ := Config().GetFilePath(exampleFileName); exampleConfigFilePath != "" {
|
if exampleConfigFilePath, _ := Config().GetFilePath(exampleFileName); exampleConfigFilePath != "" {
|
||||||
panic(gerror.Wrapf(
|
panic(gerror.WrapCodef(
|
||||||
|
gerror.CodeMissingConfiguration,
|
||||||
err,
|
err,
|
||||||
`configuration file "%s" not found, but found "%s", did you miss renaming the example configuration file?`,
|
`configuration file "%s" not found, but found "%s", did you miss renaming the example configuration file?`,
|
||||||
Config().GetFileName(),
|
Config().GetFileName(),
|
||||||
exampleFileName,
|
exampleFileName,
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
panic(gerror.Wrapf(
|
panic(gerror.WrapCodef(
|
||||||
|
gerror.CodeMissingConfiguration,
|
||||||
err,
|
err,
|
||||||
`configuration file "%s" not found, did you miss the configuration file or the misspell the configuration file name?`,
|
`configuration file "%s" not found, did you miss the configuration file or the misspell the configuration file name?`,
|
||||||
Config().GetFileName(),
|
Config().GetFileName(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
panic(gerror.Wrapf(
|
panic(gerror.WrapCodef(
|
||||||
|
gerror.CodeMissingConfiguration,
|
||||||
err,
|
err,
|
||||||
`database initialization failed: "%s" node not found, is configuration file or configuration node missing?`,
|
`database initialization failed: "%s" node not found, is configuration file or configuration node missing?`,
|
||||||
configNodeNameDatabase,
|
configNodeNameDatabase,
|
||||||
|
@ -101,7 +101,7 @@ func (m *Manager) SetPath(path string) error {
|
|||||||
} else {
|
} else {
|
||||||
realPath, _ := gfile.Search(path)
|
realPath, _ := gfile.Search(path)
|
||||||
if realPath == "" {
|
if realPath == "" {
|
||||||
return gerror.Newf(`%s does not exist`, path)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, `%s does not exist`, path)
|
||||||
}
|
}
|
||||||
m.options.Path = realPath
|
m.options.Path = realPath
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,8 @@
|
|||||||
package structs
|
package structs
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gogf/gf/errors/gerror"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -49,9 +50,11 @@ exitLoop:
|
|||||||
reflectKind = reflectValue.Kind()
|
reflectKind = reflectValue.Kind()
|
||||||
}
|
}
|
||||||
if reflectKind != reflect.Struct {
|
if reflectKind != reflect.Struct {
|
||||||
return nil, gerror.Newf(
|
return nil, errors.New(
|
||||||
|
fmt.Sprintf(
|
||||||
`invalid object kind "%s", kind of "struct" is required`,
|
`invalid object kind "%s", kind of "struct" is required`,
|
||||||
reflectKind,
|
reflectKind,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
reflectType = reflectValue.Type()
|
reflectType = reflectValue.Type()
|
||||||
|
@ -26,6 +26,7 @@ func niceCallFunc(f func()) {
|
|||||||
switch exception {
|
switch exception {
|
||||||
case exceptionExit, exceptionExitAll:
|
case exceptionExit, exceptionExitAll:
|
||||||
return
|
return
|
||||||
|
|
||||||
default:
|
default:
|
||||||
if _, ok := exception.(errorStack); ok {
|
if _, ok := exception.(errorStack); ok {
|
||||||
// It's already an error that has stack info.
|
// It's already an error that has stack info.
|
||||||
@ -35,9 +36,13 @@ func niceCallFunc(f func()) {
|
|||||||
// Note that there's a skip pointing the start stacktrace
|
// Note that there's a skip pointing the start stacktrace
|
||||||
// of the real error point.
|
// of the real error point.
|
||||||
if err, ok := exception.(error); ok {
|
if err, ok := exception.(error); ok {
|
||||||
|
if gerror.Code(err) != gerror.CodeNil {
|
||||||
panic(gerror.Wrap(err, ""))
|
panic(gerror.Wrap(err, ""))
|
||||||
} else {
|
} else {
|
||||||
panic(gerror.NewSkipf(1, "%v", exception))
|
panic(gerror.WrapCode(gerror.CodeInternalError, err, ""))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -27,8 +27,12 @@ func MiddlewareHandlerResponse(r *Request) {
|
|||||||
)
|
)
|
||||||
res, err = r.GetHandlerResponse()
|
res, err = r.GetHandlerResponse()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
code := gerror.Code(err)
|
||||||
|
if code == gerror.CodeNil {
|
||||||
|
code = gerror.CodeInternalError
|
||||||
|
}
|
||||||
internalErr = r.Response.WriteJson(DefaultHandlerResponse{
|
internalErr = r.Response.WriteJson(DefaultHandlerResponse{
|
||||||
Code: gerror.Code(err),
|
Code: code,
|
||||||
Message: err.Error(),
|
Message: err.Error(),
|
||||||
Data: nil,
|
Data: nil,
|
||||||
})
|
})
|
||||||
@ -38,7 +42,7 @@ func MiddlewareHandlerResponse(r *Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
internalErr = r.Response.WriteJson(DefaultHandlerResponse{
|
internalErr = r.Response.WriteJson(DefaultHandlerResponse{
|
||||||
Code: 0,
|
Code: gerror.CodeOk,
|
||||||
Message: "",
|
Message: "",
|
||||||
Data: res,
|
Data: res,
|
||||||
})
|
})
|
||||||
|
@ -127,7 +127,7 @@ func (m *middleware) Next() {
|
|||||||
// Create a new error with stack info.
|
// Create a new error with stack info.
|
||||||
// Note that there's a skip pointing the start stacktrace
|
// Note that there's a skip pointing the start stacktrace
|
||||||
// of the real error point.
|
// of the real error point.
|
||||||
m.request.error = gerror.WrapSkip(1, exception, "")
|
m.request.error = gerror.WrapCodeSkip(gerror.CodeInternalError, 1, exception, "")
|
||||||
}
|
}
|
||||||
m.request.Response.WriteStatus(http.StatusInternalServerError, exception)
|
m.request.Response.WriteStatus(http.StatusInternalServerError, exception)
|
||||||
loop = false
|
loop = false
|
||||||
|
@ -35,14 +35,17 @@ type UploadFiles []*UploadFile
|
|||||||
// Note that it will OVERWRITE the target file if there's already a same name file exist.
|
// Note that it will OVERWRITE the target file if there's already a same name file exist.
|
||||||
func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename string, err error) {
|
func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename string, err error) {
|
||||||
if f == nil {
|
if f == nil {
|
||||||
return "", gerror.New("file is empty, maybe you retrieve it from invalid field name or form enctype")
|
return "", gerror.NewCode(
|
||||||
|
gerror.CodeMissingParameter,
|
||||||
|
"file is empty, maybe you retrieve it from invalid field name or form enctype",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if !gfile.Exists(dirPath) {
|
if !gfile.Exists(dirPath) {
|
||||||
if err = gfile.Mkdir(dirPath); err != nil {
|
if err = gfile.Mkdir(dirPath); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else if !gfile.IsDir(dirPath) {
|
} else if !gfile.IsDir(dirPath) {
|
||||||
return "", gerror.New(`parameter "dirPath" should be a directory path`)
|
return "", gerror.NewCode(gerror.CodeInvalidParameter, `parameter "dirPath" should be a directory path`)
|
||||||
}
|
}
|
||||||
|
|
||||||
file, err := f.Open()
|
file, err := f.Open()
|
||||||
@ -76,7 +79,10 @@ func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename stri
|
|||||||
// The parameter <randomlyRename> specifies whether randomly renames all the file names.
|
// The parameter <randomlyRename> specifies whether randomly renames all the file names.
|
||||||
func (fs UploadFiles) Save(dirPath string, randomlyRename ...bool) (filenames []string, err error) {
|
func (fs UploadFiles) Save(dirPath string, randomlyRename ...bool) (filenames []string, err error) {
|
||||||
if len(fs) == 0 {
|
if len(fs) == 0 {
|
||||||
return nil, gerror.New("file array is empty, maybe you retrieve it from invalid field name or form enctype")
|
return nil, gerror.NewCode(
|
||||||
|
gerror.CodeMissingParameter,
|
||||||
|
"file array is empty, maybe you retrieve it from invalid field name or form enctype",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
for _, f := range fs {
|
for _, f := range fs {
|
||||||
if filename, err := f.Save(dirPath, randomlyRename...); err != nil {
|
if filename, err := f.Save(dirPath, randomlyRename...); err != nil {
|
||||||
|
@ -125,7 +125,7 @@ func (s *Server) Start() error {
|
|||||||
|
|
||||||
// Server can only be run once.
|
// Server can only be run once.
|
||||||
if s.Status() == ServerStatusRunning {
|
if s.Status() == ServerStatusRunning {
|
||||||
return gerror.New("server is already running")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "server is already running")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logging path setting check.
|
// Logging path setting check.
|
||||||
@ -141,7 +141,7 @@ func (s *Server) Start() error {
|
|||||||
path = gfile.Join(s.config.SessionPath, s.name)
|
path = gfile.Join(s.config.SessionPath, s.name)
|
||||||
if !gfile.Exists(path) {
|
if !gfile.Exists(path) {
|
||||||
if err := gfile.Mkdir(path); err != nil {
|
if err := gfile.Mkdir(path); err != nil {
|
||||||
return gerror.Wrapf(err, `mkdir failed for "%s"`, path)
|
return gerror.WrapCodef(gerror.CodeInternalError, err, `mkdir failed for "%s"`, path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -175,7 +175,10 @@ func (s *Server) Start() error {
|
|||||||
// If there's no route registered and no static service enabled,
|
// If there's no route registered and no static service enabled,
|
||||||
// it then returns an error of invalid usage of server.
|
// it then returns an error of invalid usage of server.
|
||||||
if len(s.routesMap) == 0 && !s.config.FileServerEnabled {
|
if len(s.routesMap) == 0 && !s.config.FileServerEnabled {
|
||||||
return gerror.New(`there's no route set or static feature enabled, did you forget import the router?`)
|
return gerror.NewCode(
|
||||||
|
gerror.CodeInvalidOperation,
|
||||||
|
`there's no route set or static feature enabled, did you forget import the router?`,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the HTTP server.
|
// Start the HTTP server.
|
||||||
|
@ -52,7 +52,7 @@ var serverProcessStatus = gtype.NewInt()
|
|||||||
// The optional parameter <newExeFilePath> specifies the new binary file for creating process.
|
// The optional parameter <newExeFilePath> specifies the new binary file for creating process.
|
||||||
func RestartAllServer(newExeFilePath ...string) error {
|
func RestartAllServer(newExeFilePath ...string) error {
|
||||||
if !gracefulEnabled {
|
if !gracefulEnabled {
|
||||||
return gerror.New("graceful reload feature is disabled")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "graceful reload feature is disabled")
|
||||||
}
|
}
|
||||||
serverActionLocker.Lock()
|
serverActionLocker.Lock()
|
||||||
defer serverActionLocker.Unlock()
|
defer serverActionLocker.Unlock()
|
||||||
@ -85,9 +85,10 @@ func checkProcessStatus() error {
|
|||||||
if status > 0 {
|
if status > 0 {
|
||||||
switch status {
|
switch status {
|
||||||
case adminActionRestarting:
|
case adminActionRestarting:
|
||||||
return gerror.New("server is restarting")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "server is restarting")
|
||||||
|
|
||||||
case adminActionShuttingDown:
|
case adminActionShuttingDown:
|
||||||
return gerror.New("server is shutting down")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "server is shutting down")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@ -98,7 +99,11 @@ func checkProcessStatus() error {
|
|||||||
func checkActionFrequency() error {
|
func checkActionFrequency() error {
|
||||||
interval := gtime.TimestampMilli() - serverActionLastTime.Val()
|
interval := gtime.TimestampMilli() - serverActionLastTime.Val()
|
||||||
if interval < adminActionIntervalLimit {
|
if interval < adminActionIntervalLimit {
|
||||||
return gerror.Newf("too frequent action, please retry in %d ms", adminActionIntervalLimit-interval)
|
return gerror.NewCodef(
|
||||||
|
gerror.CodeInvalidOperation,
|
||||||
|
"too frequent action, please retry in %d ms",
|
||||||
|
adminActionIntervalLimit-interval,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
serverActionLastTime.Set(gtime.TimestampMilli())
|
serverActionLastTime.Set(gtime.TimestampMilli())
|
||||||
return nil
|
return nil
|
||||||
|
@ -122,7 +122,7 @@ func (s *gracefulServer) ListenAndServeTLS(certFile, keyFile string, tlsConfig .
|
|||||||
|
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return gerror.Newf(`open cert file "%s","%s" failed: %s`, certFile, keyFile, err.Error())
|
return gerror.WrapCodef(gerror.CodeInternalError, err, `open cert file "%s","%s" failed`, certFile, keyFile)
|
||||||
}
|
}
|
||||||
ln, err := s.getNetListener()
|
ln, err := s.getNetListener()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -67,9 +67,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
if exception := recover(); exception != nil {
|
if exception := recover(); exception != nil {
|
||||||
request.Response.WriteStatus(http.StatusInternalServerError)
|
request.Response.WriteStatus(http.StatusInternalServerError)
|
||||||
if err, ok := exception.(error); ok {
|
if err, ok := exception.(error); ok {
|
||||||
|
if code := gerror.Code(err); code != gerror.CodeNil {
|
||||||
s.handleErrorLog(gerror.Wrap(err, ""), request)
|
s.handleErrorLog(gerror.Wrap(err, ""), request)
|
||||||
} else {
|
} else {
|
||||||
s.handleErrorLog(gerror.Newf("%v", exception), request)
|
s.handleErrorLog(gerror.WrapCode(gerror.CodeInternalError, err, ""), request)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s.handleErrorLog(gerror.NewCodef(gerror.CodeInternalError, "%v", exception), request)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -53,7 +53,7 @@ func (s *Server) parsePattern(pattern string) (domain, method, path string, err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if path == "" {
|
if path == "" {
|
||||||
err = gerror.New("invalid pattern: URI should not be empty")
|
err = gerror.NewCode(gerror.CodeInvalidParameter, "invalid pattern: URI should not be empty")
|
||||||
}
|
}
|
||||||
if path != "/" {
|
if path != "/" {
|
||||||
path = strings.TrimRight(path, "/")
|
path = strings.TrimRight(path, "/")
|
||||||
|
@ -128,12 +128,14 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN
|
|||||||
reflectType := reflect.TypeOf(f)
|
reflectType := reflect.TypeOf(f)
|
||||||
if reflectType.NumIn() == 0 || reflectType.NumIn() > 2 || reflectType.NumOut() > 2 {
|
if reflectType.NumIn() == 0 || reflectType.NumIn() > 2 || reflectType.NumOut() > 2 {
|
||||||
if pkgPath != "" {
|
if pkgPath != "" {
|
||||||
err = gerror.Newf(
|
err = gerror.NewCodef(
|
||||||
|
gerror.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`,
|
`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(),
|
pkgPath, objName, methodName, reflect.TypeOf(f).String(),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
err = gerror.Newf(
|
err = gerror.NewCodef(
|
||||||
|
gerror.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`,
|
`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(),
|
reflect.TypeOf(f).String(),
|
||||||
)
|
)
|
||||||
@ -142,7 +144,8 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN
|
|||||||
}
|
}
|
||||||
|
|
||||||
if reflectType.In(0).String() != "context.Context" {
|
if reflectType.In(0).String() != "context.Context" {
|
||||||
err = gerror.Newf(
|
err = gerror.NewCodef(
|
||||||
|
gerror.CodeInvalidParameter,
|
||||||
`invalid handler: defined as "%s", but the first input parameter should be type of "context.Context"`,
|
`invalid handler: defined as "%s", but the first input parameter should be type of "context.Context"`,
|
||||||
reflect.TypeOf(f).String(),
|
reflect.TypeOf(f).String(),
|
||||||
)
|
)
|
||||||
@ -150,7 +153,8 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, objName, methodN
|
|||||||
}
|
}
|
||||||
|
|
||||||
if reflectType.NumOut() > 0 && reflectType.Out(reflectType.NumOut()-1).String() != "error" {
|
if reflectType.NumOut() > 0 && reflectType.Out(reflectType.NumOut()-1).String() != "error" {
|
||||||
err = gerror.Newf(
|
err = gerror.NewCodef(
|
||||||
|
gerror.CodeInvalidParameter,
|
||||||
`invalid handler: defined as "%s", but the last output parameter should be type of "error"`,
|
`invalid handler: defined as "%s", but the last output parameter should be type of "error"`,
|
||||||
reflect.TypeOf(f).String(),
|
reflect.TypeOf(f).String(),
|
||||||
)
|
)
|
||||||
|
@ -242,27 +242,27 @@ func (c *Client) SetProxy(proxyURL string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTlsKeyCrt sets the certificate and key file for TLS configuration of client.
|
// SetTLSKeyCrt sets the certificate and key file for TLS configuration of client.
|
||||||
func (c *Client) SetTLSKeyCrt(crtFile, keyFile string) error {
|
func (c *Client) SetTLSKeyCrt(crtFile, keyFile string) error {
|
||||||
tlsConfig, err := LoadKeyCrt(crtFile, keyFile)
|
tlsConfig, err := LoadKeyCrt(crtFile, keyFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return gerror.WrapCode(gerror.CodeInternalError, err, "LoadKeyCrt failed")
|
||||||
}
|
}
|
||||||
if v, ok := c.Transport.(*http.Transport); ok {
|
if v, ok := c.Transport.(*http.Transport); ok {
|
||||||
tlsConfig.InsecureSkipVerify = true
|
tlsConfig.InsecureSkipVerify = true
|
||||||
v.TLSClientConfig = tlsConfig
|
v.TLSClientConfig = tlsConfig
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return gerror.New(`cannot set TLSClientConfig for custom Transport of the client`)
|
return gerror.NewCode(gerror.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTlsConfig sets the TLS configuration of client.
|
// SetTLSConfig sets the TLS configuration of client.
|
||||||
func (c *Client) SetTLSConfig(tlsConfig *tls.Config) error {
|
func (c *Client) SetTLSConfig(tlsConfig *tls.Config) error {
|
||||||
if v, ok := c.Transport.(*http.Transport); ok {
|
if v, ok := c.Transport.(*http.Transport); ok {
|
||||||
v.TLSClientConfig = tlsConfig
|
v.TLSClientConfig = tlsConfig
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return gerror.New(`cannot set TLSClientConfig for custom Transport of the client`)
|
return gerror.NewCode(gerror.CodeInternalError, `cannot set TLSClientConfig for custom Transport of the client`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadKeyCrt creates and returns a TLS configuration object with given certificate and key files.
|
// LoadKeyCrt creates and returns a TLS configuration object with given certificate and key files.
|
||||||
|
@ -188,7 +188,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 {
|
if len(array[1]) > 6 && strings.Compare(array[1][0:6], "@file:") == 0 {
|
||||||
path := array[1][6:]
|
path := array[1][6:]
|
||||||
if !gfile.Exists(path) {
|
if !gfile.Exists(path) {
|
||||||
return nil, gerror.Newf(`"%s" does not exist`, path)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path)
|
||||||
}
|
}
|
||||||
if file, err := writer.CreateFormFile(array[0], gfile.Basename(path)); err == nil {
|
if file, err := writer.CreateFormFile(array[0], gfile.Basename(path)); err == nil {
|
||||||
if f, err := os.Open(path); err == nil {
|
if f, err := os.Open(path); err == nil {
|
||||||
|
@ -38,7 +38,7 @@ func GetIntranetIp() (ip string, err error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if len(ips) == 0 {
|
if len(ips) == 0 {
|
||||||
return "", gerror.New("no intranet ip found")
|
return "", gerror.NewCode(gerror.CodeOperationFailed, "no intranet ip found")
|
||||||
}
|
}
|
||||||
return ips[0], nil
|
return ips[0], nil
|
||||||
}
|
}
|
||||||
|
@ -116,7 +116,7 @@ func (s *Server) Close() error {
|
|||||||
// Run starts running the TCP Server.
|
// Run starts running the TCP Server.
|
||||||
func (s *Server) Run() (err error) {
|
func (s *Server) Run() (err error) {
|
||||||
if s.handler == nil {
|
if s.handler == nil {
|
||||||
err = gerror.New("start running failed: socket handler not defined")
|
err = gerror.NewCode(gerror.CodeMissingConfiguration, "start running failed: socket handler not defined")
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -78,7 +78,7 @@ func (s *Server) Close() error {
|
|||||||
// Run starts listening UDP connection.
|
// Run starts listening UDP connection.
|
||||||
func (s *Server) Run() error {
|
func (s *Server) Run() error {
|
||||||
if s.handler == nil {
|
if s.handler == nil {
|
||||||
err := gerror.New("start running failed: socket handler not defined")
|
err := gerror.NewCode(gerror.CodeMissingConfiguration, "start running failed: socket handler not defined")
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -142,7 +142,7 @@ func (c *Config) SetPath(path string) error {
|
|||||||
} else {
|
} else {
|
||||||
buffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" does not exist`, path))
|
buffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" does not exist`, path))
|
||||||
}
|
}
|
||||||
err := gerror.New(buffer.String())
|
err := gerror.NewCode(gerror.CodeOperationFailed, buffer.String())
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
@ -219,14 +219,14 @@ func (c *Config) AddPath(path string) error {
|
|||||||
} else {
|
} else {
|
||||||
buffer.WriteString(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" does not exist`, path))
|
buffer.WriteString(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" does not exist`, path))
|
||||||
}
|
}
|
||||||
err := gerror.New(buffer.String())
|
err := gerror.NewCode(gerror.CodeOperationFailed, buffer.String())
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !isDir {
|
if !isDir {
|
||||||
err := gerror.Newf(`[gcfg] AddPath failed: path "%s" should be directory type`, path)
|
err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gcfg] AddPath failed: path "%s" should be directory type`, path)
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
@ -329,7 +329,7 @@ func (c *Config) GetFilePath(file ...string) (path string, err error) {
|
|||||||
} else {
|
} else {
|
||||||
buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" with no path configured", name))
|
buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" with no path configured", name))
|
||||||
}
|
}
|
||||||
err = gerror.New(buffer.String())
|
err = gerror.NewCode(gerror.CodeOperationFailed, buffer.String())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -295,7 +295,7 @@ func (c *Config) GetStruct(pattern string, pointer interface{}, mapping ...map[s
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.GetStruct(pattern, pointer, mapping...)
|
return j.GetStruct(pattern, pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetStructs converts any slice to given struct slice.
|
// GetStructs converts any slice to given struct slice.
|
||||||
@ -303,7 +303,7 @@ func (c *Config) GetStructs(pattern string, pointer interface{}, mapping ...map[
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.GetStructs(pattern, pointer, mapping...)
|
return j.GetStructs(pattern, pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMapToMap retrieves the value by specified `pattern` and converts it to specified map variable.
|
// GetMapToMap retrieves the value by specified `pattern` and converts it to specified map variable.
|
||||||
@ -312,7 +312,7 @@ func (c *Config) GetMapToMap(pattern string, pointer interface{}, mapping ...map
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.GetMapToMap(pattern, pointer, mapping...)
|
return j.GetMapToMap(pattern, pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMapToMaps retrieves the value by specified `pattern` and converts it to specified map slice
|
// GetMapToMaps retrieves the value by specified `pattern` and converts it to specified map slice
|
||||||
@ -322,7 +322,7 @@ func (c *Config) GetMapToMaps(pattern string, pointer interface{}, mapping ...ma
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.GetMapToMaps(pattern, pointer, mapping...)
|
return j.GetMapToMaps(pattern, pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMapToMapsDeep retrieves the value by specified `pattern` and converts it to specified map slice
|
// GetMapToMapsDeep retrieves the value by specified `pattern` and converts it to specified map slice
|
||||||
@ -332,7 +332,7 @@ func (c *Config) GetMapToMapsDeep(pattern string, pointer interface{}, mapping .
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.GetMapToMapsDeep(pattern, pointer, mapping...)
|
return j.GetMapToMapsDeep(pattern, pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map converts current Json object to map[string]interface{}. It returns nil if fails.
|
// Map converts current Json object to map[string]interface{}. It returns nil if fails.
|
||||||
@ -358,7 +358,7 @@ func (c *Config) Struct(pointer interface{}, mapping ...map[string]string) error
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.Struct(pointer, mapping...)
|
return j.Struct(pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Structs converts current Json object to specified object slice.
|
// Structs converts current Json object to specified object slice.
|
||||||
@ -367,7 +367,7 @@ func (c *Config) Structs(pointer interface{}, mapping ...map[string]string) erro
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.Structs(pointer, mapping...)
|
return j.Structs(pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// MapToMap converts current Json object to specified map variable.
|
// MapToMap converts current Json object to specified map variable.
|
||||||
@ -376,7 +376,7 @@ func (c *Config) MapToMap(pointer interface{}, mapping ...map[string]string) err
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.MapToMap(pointer, mapping...)
|
return j.MapToMap(pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// MapToMaps converts current Json object to specified map variable slice.
|
// MapToMaps converts current Json object to specified map variable slice.
|
||||||
@ -385,7 +385,7 @@ func (c *Config) MapToMaps(pointer interface{}, mapping ...map[string]string) er
|
|||||||
if j := c.getJson(); j != nil {
|
if j := c.getJson(); j != nil {
|
||||||
return j.MapToMaps(pointer, mapping...)
|
return j.MapToMaps(pointer, mapping...)
|
||||||
}
|
}
|
||||||
return gerror.New("configuration not found")
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "configuration not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear removes all parsed configuration files content cache,
|
// Clear removes all parsed configuration files content cache,
|
||||||
|
@ -14,14 +14,14 @@ import (
|
|||||||
// BindHandle registers callback function <f> with <cmd>.
|
// BindHandle registers callback function <f> with <cmd>.
|
||||||
func BindHandle(cmd string, f func()) error {
|
func BindHandle(cmd string, f func()) error {
|
||||||
if _, ok := defaultCommandFuncMap[cmd]; ok {
|
if _, ok := defaultCommandFuncMap[cmd]; ok {
|
||||||
return gerror.New("duplicated handle for command:" + cmd)
|
return gerror.NewCode(gerror.CodeInvalidOperation, "duplicated handle for command:"+cmd)
|
||||||
} else {
|
} else {
|
||||||
defaultCommandFuncMap[cmd] = f
|
defaultCommandFuncMap[cmd] = f
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// BindHandle registers callback function with map <m>.
|
// BindHandleMap registers callback function with map <m>.
|
||||||
func BindHandleMap(m map[string]func()) error {
|
func BindHandleMap(m map[string]func()) error {
|
||||||
var err error
|
var err error
|
||||||
for k, v := range m {
|
for k, v := range m {
|
||||||
@ -37,7 +37,7 @@ func RunHandle(cmd string) error {
|
|||||||
if handle, ok := defaultCommandFuncMap[cmd]; ok {
|
if handle, ok := defaultCommandFuncMap[cmd]; ok {
|
||||||
handle()
|
handle()
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no handle found for command:" + cmd)
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -49,10 +49,10 @@ func AutoRun() error {
|
|||||||
if handle, ok := defaultCommandFuncMap[cmd]; ok {
|
if handle, ok := defaultCommandFuncMap[cmd]; ok {
|
||||||
handle()
|
handle()
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no handle found for command:" + cmd)
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no command found")
|
return gerror.NewCode(gerror.CodeMissingParameter, "no command found")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -94,7 +94,7 @@ func ParseWithArgs(args []string, supportedOptions map[string]bool, strict ...bo
|
|||||||
i++
|
i++
|
||||||
continue
|
continue
|
||||||
} else if parser.strict {
|
} else if parser.strict {
|
||||||
return nil, gerror.Newf(`invalid option '%s'`, args[i])
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid option '%s'`, args[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ import (
|
|||||||
// BindHandle registers callback function <f> with <cmd>.
|
// BindHandle registers callback function <f> with <cmd>.
|
||||||
func (p *Parser) BindHandle(cmd string, f func()) error {
|
func (p *Parser) BindHandle(cmd string, f func()) error {
|
||||||
if _, ok := p.commandFuncMap[cmd]; ok {
|
if _, ok := p.commandFuncMap[cmd]; ok {
|
||||||
return gerror.New("duplicated handle for command:" + cmd)
|
return gerror.NewCode(gerror.CodeInvalidOperation, "duplicated handle for command:"+cmd)
|
||||||
} else {
|
} else {
|
||||||
p.commandFuncMap[cmd] = f
|
p.commandFuncMap[cmd] = f
|
||||||
}
|
}
|
||||||
@ -37,7 +37,7 @@ func (p *Parser) RunHandle(cmd string) error {
|
|||||||
if handle, ok := p.commandFuncMap[cmd]; ok {
|
if handle, ok := p.commandFuncMap[cmd]; ok {
|
||||||
handle()
|
handle()
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no handle found for command:" + cmd)
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -49,10 +49,10 @@ func (p *Parser) AutoRun() error {
|
|||||||
if handle, ok := p.commandFuncMap[cmd]; ok {
|
if handle, ok := p.commandFuncMap[cmd]; ok {
|
||||||
handle()
|
handle()
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no handle found for command:" + cmd)
|
return gerror.NewCode(gerror.CodeMissingConfiguration, "no handle found for command:"+cmd)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return gerror.New("no command found")
|
return gerror.NewCode(gerror.CodeMissingParameter, "no command found")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -62,7 +62,7 @@ func (c *Cron) GetLogLevel() int {
|
|||||||
func (c *Cron) Add(pattern string, job func(), name ...string) (*Entry, error) {
|
func (c *Cron) Add(pattern string, job func(), name ...string) (*Entry, error) {
|
||||||
if len(name) > 0 {
|
if len(name) > 0 {
|
||||||
if c.Search(name[0]) != nil {
|
if c.Search(name[0]) != nil {
|
||||||
return nil, gerror.Newf(`cron job "%s" already exists`, name[0])
|
return nil, gerror.NewCodef(gerror.CodeInvalidOperation, `cron job "%s" already exists`, name[0])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return c.addEntry(pattern, job, false, name...)
|
return c.addEntry(pattern, job, false, name...)
|
||||||
|
@ -90,7 +90,7 @@ func newSchedule(pattern string) (*cronSchedule, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return nil, gerror.Newf(`invalid pattern: "%s"`, pattern)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern: "%s"`, pattern)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Handle the common cron pattern, like:
|
// Handle the common cron pattern, like:
|
||||||
@ -139,7 +139,7 @@ func newSchedule(pattern string) (*cronSchedule, error) {
|
|||||||
}
|
}
|
||||||
return schedule, nil
|
return schedule, nil
|
||||||
} else {
|
} else {
|
||||||
return nil, gerror.Newf(`invalid pattern: "%s"`, pattern)
|
return nil, gerror.NewCodef(gerror.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, "/")
|
intervalArray := strings.Split(item, "/")
|
||||||
if len(intervalArray) == 2 {
|
if len(intervalArray) == 2 {
|
||||||
if i, err := strconv.Atoi(intervalArray[1]); err != nil {
|
if i, err := strconv.Atoi(intervalArray[1]); err != nil {
|
||||||
return nil, gerror.Newf(`invalid pattern item: "%s"`, item)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item)
|
||||||
} else {
|
} else {
|
||||||
interval = i
|
interval = i
|
||||||
}
|
}
|
||||||
@ -178,7 +178,7 @@ func parseItem(item string, min int, max int, allowQuestionMark bool) (map[int]s
|
|||||||
// Eg: */5
|
// Eg: */5
|
||||||
if rangeArray[0] != "*" {
|
if rangeArray[0] != "*" {
|
||||||
if i, err := parseItemValue(rangeArray[0], fieldType); err != nil {
|
if i, err := parseItemValue(rangeArray[0], fieldType); err != nil {
|
||||||
return nil, gerror.Newf(`invalid pattern item: "%s"`, item)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item)
|
||||||
} else {
|
} else {
|
||||||
rangeMin = i
|
rangeMin = i
|
||||||
rangeMax = 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 len(rangeArray) == 2 {
|
||||||
if i, err := parseItemValue(rangeArray[1], fieldType); err != nil {
|
if i, err := parseItemValue(rangeArray[1], fieldType); err != nil {
|
||||||
return nil, gerror.Newf(`invalid pattern item: "%s"`, item)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern item: "%s"`, item)
|
||||||
} else {
|
} else {
|
||||||
rangeMax = i
|
rangeMax = i
|
||||||
}
|
}
|
||||||
@ -220,7 +220,7 @@ func parseItemValue(value string, fieldType byte) (int, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return 0, gerror.Newf(`invalid pattern value: "%s"`, value)
|
return 0, gerror.NewCodef(gerror.CodeInvalidParameter, `invalid pattern value: "%s"`, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// meet checks if the given time <t> meets the runnable point for the job.
|
// meet checks if the given time <t> meets the runnable point for the job.
|
||||||
|
@ -7,8 +7,8 @@
|
|||||||
package gfile
|
package gfile
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
@ -21,10 +21,10 @@ import (
|
|||||||
// or else it calls CopyDir.
|
// or else it calls CopyDir.
|
||||||
func Copy(src string, dst string) error {
|
func Copy(src string, dst string) error {
|
||||||
if src == "" {
|
if src == "" {
|
||||||
return errors.New("source path cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "source path cannot be empty")
|
||||||
}
|
}
|
||||||
if dst == "" {
|
if dst == "" {
|
||||||
return errors.New("destination path cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "destination path cannot be empty")
|
||||||
}
|
}
|
||||||
if IsFile(src) {
|
if IsFile(src) {
|
||||||
return CopyFile(src, dst)
|
return CopyFile(src, dst)
|
||||||
@ -40,10 +40,10 @@ func Copy(src string, dst string) error {
|
|||||||
// Thanks: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04
|
// Thanks: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04
|
||||||
func CopyFile(src, dst string) (err error) {
|
func CopyFile(src, dst string) (err error) {
|
||||||
if src == "" {
|
if src == "" {
|
||||||
return errors.New("source file cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "source file cannot be empty")
|
||||||
}
|
}
|
||||||
if dst == "" {
|
if dst == "" {
|
||||||
return errors.New("destination file cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "destination file cannot be empty")
|
||||||
}
|
}
|
||||||
// If src and dst are the same path, it does nothing.
|
// If src and dst are the same path, it does nothing.
|
||||||
if src == dst {
|
if src == dst {
|
||||||
@ -87,10 +87,10 @@ func CopyFile(src, dst string) (err error) {
|
|||||||
// Note that, the Source directory must exist and symlinks are ignored and skipped.
|
// Note that, the Source directory must exist and symlinks are ignored and skipped.
|
||||||
func CopyDir(src string, dst string) (err error) {
|
func CopyDir(src string, dst string) (err error) {
|
||||||
if src == "" {
|
if src == "" {
|
||||||
return errors.New("source directory cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "source directory cannot be empty")
|
||||||
}
|
}
|
||||||
if dst == "" {
|
if dst == "" {
|
||||||
return errors.New("destination directory cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "destination directory cannot be empty")
|
||||||
}
|
}
|
||||||
// If src and dst are the same path, it does nothing.
|
// If src and dst are the same path, it does nothing.
|
||||||
if src == dst {
|
if src == dst {
|
||||||
|
@ -8,7 +8,7 @@ package gfile
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"os/user"
|
"os/user"
|
||||||
@ -56,7 +56,7 @@ func homeUnix() (string, error) {
|
|||||||
|
|
||||||
result := strings.TrimSpace(stdout.String())
|
result := strings.TrimSpace(stdout.String())
|
||||||
if result == "" {
|
if result == "" {
|
||||||
return "", errors.New("blank output when reading home directory")
|
return "", gerror.NewCode(gerror.CodeInternalError, "blank output when reading home directory")
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
@ -73,7 +73,7 @@ func homeWindows() (string, error) {
|
|||||||
home = os.Getenv("USERPROFILE")
|
home = os.Getenv("USERPROFILE")
|
||||||
}
|
}
|
||||||
if home == "" {
|
if home == "" {
|
||||||
return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
|
return "", gerror.NewCode(gerror.CodeOperationFailed, "HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
|
||||||
}
|
}
|
||||||
|
|
||||||
return home, nil
|
return home, nil
|
||||||
|
@ -137,7 +137,7 @@ func ScanDirFileFunc(path string, pattern string, recursive bool, handler func(p
|
|||||||
// string, or else it appends the sub-file path to result slice.
|
// 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) {
|
func doScanDir(depth int, path string, pattern string, recursive bool, handler func(path string) string) ([]string, error) {
|
||||||
if depth >= maxScanDepth {
|
if depth >= maxScanDepth {
|
||||||
return nil, gerror.Newf("directory scanning exceeds max recursive depth: %d", maxScanDepth)
|
return nil, gerror.NewCodef(gerror.CodeOperationFailed, "directory scanning exceeds max recursive depth: %d", maxScanDepth)
|
||||||
}
|
}
|
||||||
list := ([]string)(nil)
|
list := ([]string)(nil)
|
||||||
file, err := os.Open(path)
|
file, err := os.Open(path)
|
||||||
|
@ -8,8 +8,8 @@ package gfile
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gogf/gf/errors/gerror"
|
||||||
|
|
||||||
"github.com/gogf/gf/container/garray"
|
"github.com/gogf/gf/container/garray"
|
||||||
)
|
)
|
||||||
@ -52,7 +52,7 @@ func Search(name string, prioritySearchPaths ...string) (realPath string, err er
|
|||||||
buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
|
buffer.WriteString(fmt.Sprintf("\n%d. %s", k+1, v))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
err = errors.New(buffer.String())
|
err = gerror.NewCode(gerror.CodeOperationFailed, buffer.String())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,8 @@
|
|||||||
package gfpool
|
package gfpool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@ -41,7 +41,7 @@ func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *
|
|||||||
// Stat returns the FileInfo structure describing file.
|
// Stat returns the FileInfo structure describing file.
|
||||||
func (f *File) Stat() (os.FileInfo, error) {
|
func (f *File) Stat() (os.FileInfo, error) {
|
||||||
if f.stat == nil {
|
if f.stat == nil {
|
||||||
return nil, errors.New("file stat is empty")
|
return nil, gerror.NewCode(gerror.CodeInternalError, "file stat is empty")
|
||||||
}
|
}
|
||||||
return f.stat, nil
|
return f.stat, nil
|
||||||
}
|
}
|
||||||
|
@ -139,7 +139,7 @@ func RemoveCallback(callbackId int) error {
|
|||||||
callback = r.(*Callback)
|
callback = r.(*Callback)
|
||||||
}
|
}
|
||||||
if callback == nil {
|
if callback == nil {
|
||||||
return gerror.Newf(`callback for id %d not found`, callbackId)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, `callback for id %d not found`, callbackId)
|
||||||
}
|
}
|
||||||
w.RemoveCallback(callbackId)
|
w.RemoveCallback(callbackId)
|
||||||
return nil
|
return nil
|
||||||
|
@ -66,7 +66,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) {
|
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.
|
// Check and convert the given path to absolute path.
|
||||||
if t := fileRealPath(path); t == "" {
|
if t := fileRealPath(path); t == "" {
|
||||||
return nil, gerror.Newf(`"%s" does not exist`, path)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path)
|
||||||
} else {
|
} else {
|
||||||
path = t
|
path = t
|
||||||
}
|
}
|
||||||
|
@ -81,7 +81,7 @@ func (l *Logger) SetConfig(config Config) error {
|
|||||||
// SetConfigWithMap set configurations with map for the logger.
|
// SetConfigWithMap set configurations with map for the logger.
|
||||||
func (l *Logger) SetConfigWithMap(m map[string]interface{}) error {
|
func (l *Logger) SetConfigWithMap(m map[string]interface{}) error {
|
||||||
if m == nil || len(m) == 0 {
|
if m == nil || len(m) == 0 {
|
||||||
return gerror.New("configuration cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "configuration cannot be empty")
|
||||||
}
|
}
|
||||||
// The m now is a shallow copy of m.
|
// The m now is a shallow copy of m.
|
||||||
// A little tricky, isn't it?
|
// A little tricky, isn't it?
|
||||||
@ -92,7 +92,7 @@ func (l *Logger) SetConfigWithMap(m map[string]interface{}) error {
|
|||||||
if level, ok := levelStringMap[strings.ToUpper(gconv.String(levelValue))]; ok {
|
if level, ok := levelStringMap[strings.ToUpper(gconv.String(levelValue))]; ok {
|
||||||
m[levelKey] = level
|
m[levelKey] = level
|
||||||
} else {
|
} else {
|
||||||
return gerror.Newf(`invalid level string: %v`, levelValue)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid level string: %v`, levelValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Change string configuration to int value for file rotation size.
|
// Change string configuration to int value for file rotation size.
|
||||||
@ -100,7 +100,7 @@ func (l *Logger) SetConfigWithMap(m map[string]interface{}) error {
|
|||||||
if rotateSizeValue != nil {
|
if rotateSizeValue != nil {
|
||||||
m[rotateSizeKey] = gfile.StrToSize(gconv.String(rotateSizeValue))
|
m[rotateSizeKey] = gfile.StrToSize(gconv.String(rotateSizeValue))
|
||||||
if m[rotateSizeKey] == -1 {
|
if m[rotateSizeKey] == -1 {
|
||||||
return gerror.Newf(`invalid rotate size: %v`, rotateSizeValue)
|
return gerror.NewCodef(gerror.CodeInvalidConfiguration, `invalid rotate size: %v`, rotateSizeValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := gconv.Struct(m, &l.config); err != nil {
|
if err := gconv.Struct(m, &l.config); err != nil {
|
||||||
@ -205,12 +205,11 @@ func (l *Logger) GetWriter() io.Writer {
|
|||||||
// SetPath sets the directory path for file logging.
|
// SetPath sets the directory path for file logging.
|
||||||
func (l *Logger) SetPath(path string) error {
|
func (l *Logger) SetPath(path string) error {
|
||||||
if path == "" {
|
if path == "" {
|
||||||
return gerror.New("logging path is empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "logging path is empty")
|
||||||
}
|
}
|
||||||
if !gfile.Exists(path) {
|
if !gfile.Exists(path) {
|
||||||
if err := gfile.Mkdir(path); err != nil {
|
if err := gfile.Mkdir(path); err != nil {
|
||||||
//fmt.Fprintln(os.Stderr, fmt.Sprintf(`[glog] mkdir "%s" failed: %s`, path, err.Error()))
|
return gerror.WrapCodef(gerror.CodeOperationFailed, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd())
|
||||||
return gerror.Wrapf(err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
l.config.Path = strings.TrimRight(path, gfile.Separator)
|
l.config.Path = strings.TrimRight(path, gfile.Separator)
|
||||||
|
@ -77,7 +77,7 @@ func (l *Logger) SetLevelStr(levelStr string) error {
|
|||||||
if level, ok := levelStringMap[strings.ToUpper(levelStr)]; ok {
|
if level, ok := levelStringMap[strings.ToUpper(levelStr)]; ok {
|
||||||
l.config.Level = level
|
l.config.Level = level
|
||||||
} else {
|
} else {
|
||||||
return gerror.Newf(`invalid level string: %s`, levelStr)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid level string: %s`, levelStr)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -65,7 +65,7 @@ func getConnByPid(pid int) (*gtcp.PoolConn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, gerror.Newf("could not find port for pid: %d", pid)
|
return nil, gerror.NewCodef(gerror.CodeOperationFailed, "could not find port for pid: %d", pid)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getPortByPid returns the listening port for specified pid.
|
// getPortByPid returns the listening port for specified pid.
|
||||||
|
@ -43,8 +43,7 @@ func Send(pid int, data []byte, group ...string) error {
|
|||||||
})
|
})
|
||||||
if len(result) > 0 {
|
if len(result) > 0 {
|
||||||
response := new(MsgResponse)
|
response := new(MsgResponse)
|
||||||
err = json.UnmarshalUseNumber(result, response)
|
if err = json.UnmarshalUseNumber(result, response); err == nil {
|
||||||
if err == nil {
|
|
||||||
if response.Code != 1 {
|
if response.Code != 1 {
|
||||||
err = gerror.New(response.Message)
|
err = gerror.New(response.Message)
|
||||||
}
|
}
|
||||||
|
@ -101,7 +101,7 @@ func (p *Process) Send(data []byte) error {
|
|||||||
if p.Process != nil {
|
if p.Process != nil {
|
||||||
return Send(p.Process.Pid, data)
|
return Send(p.Process.Pid, data)
|
||||||
}
|
}
|
||||||
return gerror.New("invalid process")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "invalid process")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Release releases any resources associated with the Process p,
|
// Release releases any resources associated with the Process p,
|
||||||
|
@ -69,7 +69,7 @@ func Jobs() int {
|
|||||||
// The job will be executed asynchronously.
|
// The job will be executed asynchronously.
|
||||||
func (p *Pool) Add(f func()) error {
|
func (p *Pool) Add(f func()) error {
|
||||||
for p.closed.Val() {
|
for p.closed.Val() {
|
||||||
return gerror.New("pool closed")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "pool closed")
|
||||||
}
|
}
|
||||||
p.list.PushFront(f)
|
p.list.PushFront(f)
|
||||||
// Check whether fork new goroutine or not.
|
// Check whether fork new goroutine or not.
|
||||||
@ -96,9 +96,13 @@ func (p *Pool) Add(f func()) error {
|
|||||||
func (p *Pool) AddWithRecover(userFunc func(), recoverFunc ...func(err error)) error {
|
func (p *Pool) AddWithRecover(userFunc func(), recoverFunc ...func(err error)) error {
|
||||||
return p.Add(func() {
|
return p.Add(func() {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if exception := recover(); exception != nil {
|
||||||
if len(recoverFunc) > 0 && recoverFunc[0] != nil {
|
if len(recoverFunc) > 0 && recoverFunc[0] != nil {
|
||||||
recoverFunc[0](gerror.Newf(`%v`, err))
|
if err, ok := exception.(error); ok {
|
||||||
|
recoverFunc[0](err)
|
||||||
|
} else {
|
||||||
|
recoverFunc[0](gerror.NewCodef(gerror.CodeInternalError, `%v`, exception))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
@ -8,12 +8,15 @@
|
|||||||
package gsession
|
package gsession
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"github.com/gogf/gf/util/guid"
|
"github.com/gogf/gf/util/guid"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrorDisabled = errors.New("this feature is disabled in this storage")
|
ErrorDisabled = gerror.NewOption(gerror.Option{
|
||||||
|
Text: "this feature is disabled in this storage",
|
||||||
|
Code: gerror.CodeNotSupported,
|
||||||
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewSessionId creates and returns a new and unique session id string,
|
// NewSessionId creates and returns a new and unique session id string,
|
||||||
|
@ -182,7 +182,7 @@ func (s *Session) Id() string {
|
|||||||
// It returns error if it is called after session starts.
|
// It returns error if it is called after session starts.
|
||||||
func (s *Session) SetId(id string) error {
|
func (s *Session) SetId(id string) error {
|
||||||
if s.start {
|
if s.start {
|
||||||
return gerror.New("session already started")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "session already started")
|
||||||
}
|
}
|
||||||
s.id = id
|
s.id = id
|
||||||
return nil
|
return nil
|
||||||
@ -192,7 +192,7 @@ func (s *Session) SetId(id string) error {
|
|||||||
// It returns error if it is called after session starts.
|
// It returns error if it is called after session starts.
|
||||||
func (s *Session) SetIdFunc(f func(ttl time.Duration) string) error {
|
func (s *Session) SetIdFunc(f func(ttl time.Duration) string) error {
|
||||||
if s.start {
|
if s.start {
|
||||||
return gerror.New("session already started")
|
return gerror.NewCode(gerror.CodeInvalidOperation, "session already started")
|
||||||
}
|
}
|
||||||
s.idFunc = f
|
s.idFunc = f
|
||||||
return nil
|
return nil
|
||||||
|
@ -48,15 +48,15 @@ func NewStorageFile(path ...string) *StorageFile {
|
|||||||
if len(path) > 0 && path[0] != "" {
|
if len(path) > 0 && path[0] != "" {
|
||||||
storagePath, _ = gfile.Search(path[0])
|
storagePath, _ = gfile.Search(path[0])
|
||||||
if storagePath == "" {
|
if storagePath == "" {
|
||||||
panic(gerror.Newf("'%s' does not exist", path[0]))
|
panic(gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" does not exist`, path[0]))
|
||||||
}
|
}
|
||||||
if !gfile.IsWritable(storagePath) {
|
if !gfile.IsWritable(storagePath) {
|
||||||
panic(gerror.Newf("'%s' is not writable", path[0]))
|
panic(gerror.NewCodef(gerror.CodeInvalidParameter, `"%s" is not writable`, path[0]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if storagePath != "" {
|
if storagePath != "" {
|
||||||
if err := gfile.Mkdir(storagePath); err != nil {
|
if err := gfile.Mkdir(storagePath); err != nil {
|
||||||
panic(gerror.Wrapf(err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd()))
|
panic(gerror.WrapCodef(gerror.CodeInternalError, err, `Mkdir "%s" failed in PWD "%s"`, path, gfile.Pwd()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s := &StorageFile{
|
s := &StorageFile{
|
||||||
|
@ -103,7 +103,7 @@ func (sp *SPath) Set(path string) (realPath string, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if realPath == "" {
|
if realPath == "" {
|
||||||
return realPath, gerror.Newf(`path "%s" does not exist`, path)
|
return realPath, gerror.NewCodef(gerror.CodeInvalidParameter, `path "%s" does not exist`, path)
|
||||||
}
|
}
|
||||||
// The set path must be a directory.
|
// The set path must be a directory.
|
||||||
if gfile.IsDir(realPath) {
|
if gfile.IsDir(realPath) {
|
||||||
@ -123,7 +123,7 @@ func (sp *SPath) Set(path string) (realPath string, err error) {
|
|||||||
sp.addMonitorByPath(realPath)
|
sp.addMonitorByPath(realPath)
|
||||||
return realPath, nil
|
return realPath, nil
|
||||||
} else {
|
} else {
|
||||||
return "", gerror.New(path + " should be a folder")
|
return "", gerror.NewCode(gerror.CodeInvalidParameter, path+" should be a folder")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -138,7 +138,7 @@ func (sp *SPath) Add(path string) (realPath string, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if realPath == "" {
|
if realPath == "" {
|
||||||
return realPath, gerror.Newf(`path "%s" does not exist`, path)
|
return realPath, gerror.NewCodef(gerror.CodeInvalidParameter, `path "%s" does not exist`, path)
|
||||||
}
|
}
|
||||||
// The added path must be a directory.
|
// The added path must be a directory.
|
||||||
if gfile.IsDir(realPath) {
|
if gfile.IsDir(realPath) {
|
||||||
@ -152,7 +152,7 @@ func (sp *SPath) Add(path string) (realPath string, err error) {
|
|||||||
}
|
}
|
||||||
return realPath, nil
|
return realPath, nil
|
||||||
} else {
|
} else {
|
||||||
return "", gerror.New(path + " should be a folder")
|
return "", gerror.NewCode(gerror.CodeInvalidParameter, path+" should be a folder")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -276,7 +276,7 @@ func StrToTime(str string, format ...string) (*Time, error) {
|
|||||||
}
|
}
|
||||||
return NewFromTime(time.Date(0, time.Month(1), 1, hour, min, sec, nsec, local)), nil
|
return NewFromTime(time.Date(0, time.Month(1), 1, hour, min, sec, nsec, local)), nil
|
||||||
} else {
|
} else {
|
||||||
return nil, gerror.New("unsupported time format")
|
return nil, gerror.NewCode(gerror.CodeInvalidParameter, "unsupported time format")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Time
|
// Time
|
||||||
@ -311,7 +311,7 @@ func StrToTime(str string, format ...string) (*Time, error) {
|
|||||||
m, _ := strconv.Atoi(zone[2:4])
|
m, _ := strconv.Atoi(zone[2:4])
|
||||||
s, _ := strconv.Atoi(zone[4:6])
|
s, _ := strconv.Atoi(zone[4:6])
|
||||||
if h > 24 || m > 59 || s > 59 {
|
if h > 24 || m > 59 || s > 59 {
|
||||||
return nil, gerror.Newf("invalid zone string: %s", match[6])
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, "invalid zone string: %s", match[6])
|
||||||
}
|
}
|
||||||
// Comparing the given time zone whether equals to current time zone,
|
// Comparing the given time zone whether equals to current time zone,
|
||||||
// it converts it to UTC if they does not equal.
|
// it converts it to UTC if they does not equal.
|
||||||
@ -350,7 +350,7 @@ func StrToTime(str string, format ...string) (*Time, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if month <= 0 || day <= 0 {
|
if month <= 0 || day <= 0 {
|
||||||
return nil, gerror.New("invalid time string:" + str)
|
return nil, gerror.NewCodef(gerror.CodeInvalidParameter, "invalid time string:%s", str)
|
||||||
}
|
}
|
||||||
return NewFromTime(time.Date(year, time.Month(month), day, hour, min, sec, nsec, local)), nil
|
return NewFromTime(time.Date(year, time.Month(month), day, hour, min, sec, nsec, local)), nil
|
||||||
}
|
}
|
||||||
|
@ -462,7 +462,7 @@ func (t *Time) UnmarshalText(data []byte) error {
|
|||||||
*t = *vTime
|
*t = *vTime
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return gerror.Newf(`invalid time value: %s`, data)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, `invalid time value: %s`, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NoValidation marks this struct object will not be validated by package gvalid.
|
// NoValidation marks this struct object will not be validated by package gvalid.
|
||||||
|
@ -74,7 +74,7 @@ func (view *View) SetConfig(config Config) error {
|
|||||||
// SetConfigWithMap set configurations with map for the view.
|
// SetConfigWithMap set configurations with map for the view.
|
||||||
func (view *View) SetConfigWithMap(m map[string]interface{}) error {
|
func (view *View) SetConfigWithMap(m map[string]interface{}) error {
|
||||||
if m == nil || len(m) == 0 {
|
if m == nil || len(m) == 0 {
|
||||||
return gerror.New("configuration cannot be empty")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "configuration cannot be empty")
|
||||||
}
|
}
|
||||||
// The m now is a shallow copy of m.
|
// The m now is a shallow copy of m.
|
||||||
// Any changes to m does not affect the original one.
|
// Any changes to m does not affect the original one.
|
||||||
@ -123,7 +123,7 @@ func (view *View) SetPath(path string) error {
|
|||||||
}
|
}
|
||||||
// Path not exist.
|
// Path not exist.
|
||||||
if realPath == "" {
|
if realPath == "" {
|
||||||
err := gerror.Newf(`[gview] SetPath failed: path "%s" does not exist`, path)
|
err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] SetPath failed: path "%s" does not exist`, path)
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
@ -131,7 +131,7 @@ func (view *View) SetPath(path string) error {
|
|||||||
}
|
}
|
||||||
// Should be a directory.
|
// Should be a directory.
|
||||||
if !isDir {
|
if !isDir {
|
||||||
err := gerror.Newf(`[gview] SetPath failed: path "%s" should be directory type`, path)
|
err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] SetPath failed: path "%s" should be directory type`, path)
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
@ -177,7 +177,7 @@ func (view *View) AddPath(path string) error {
|
|||||||
}
|
}
|
||||||
// Path not exist.
|
// Path not exist.
|
||||||
if realPath == "" {
|
if realPath == "" {
|
||||||
err := gerror.Newf(`[gview] AddPath failed: path "%s" does not exist`, path)
|
err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] AddPath failed: path "%s" does not exist`, path)
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
@ -185,7 +185,7 @@ func (view *View) AddPath(path string) error {
|
|||||||
}
|
}
|
||||||
// realPath should be type of folder.
|
// realPath should be type of folder.
|
||||||
if !isDir {
|
if !isDir {
|
||||||
err := gerror.Newf(`[gview] AddPath failed: path "%s" should be directory type`, path)
|
err := gerror.NewCodef(gerror.CodeInvalidParameter, `[gview] AddPath failed: path "%s" should be directory type`, path)
|
||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(err)
|
glog.Error(err)
|
||||||
}
|
}
|
||||||
|
@ -112,7 +112,7 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res
|
|||||||
tpl, err = tpl.(*texttpl.Template).Parse(item.content)
|
tpl, err = tpl.(*texttpl.Template).Parse(item.content)
|
||||||
}
|
}
|
||||||
if err != nil && item.path != "" {
|
if err != nil && item.path != "" {
|
||||||
err = gerror.Wrap(err, item.path)
|
err = gerror.WrapCode(gerror.CodeInternalError, err, item.path)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -298,7 +298,7 @@ func (view *View) getTemplate(filePath, folderPath, pattern string) (tpl interfa
|
|||||||
// formatTemplateObjectCreatingError formats the error that creted from creating template object.
|
// formatTemplateObjectCreatingError formats the error that creted from creating template object.
|
||||||
func (view *View) formatTemplateObjectCreatingError(filePath, tplName string, err error) error {
|
func (view *View) formatTemplateObjectCreatingError(filePath, tplName string, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return gerror.NewSkip(1, gstr.Replace(err.Error(), tplName, filePath))
|
return gerror.NewCodeSkip(gerror.CodeInternalError, 1, gstr.Replace(err.Error(), tplName, filePath))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -376,7 +376,7 @@ func (view *View) searchFile(file string) (path string, folder string, resource
|
|||||||
if errorPrint() {
|
if errorPrint() {
|
||||||
glog.Error(buffer.String())
|
glog.Error(buffer.String())
|
||||||
}
|
}
|
||||||
err = gerror.Newf(`template file "%s" not found`, file)
|
err = gerror.NewCodef(gerror.CodeInvalidParameter, `template file "%s" not found`, file)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -86,7 +86,7 @@ func doMapToMap(params interface{}, pointer interface{}, mapping ...map[string]s
|
|||||||
pointerKind = pointerRv.Kind()
|
pointerKind = pointerRv.Kind()
|
||||||
}
|
}
|
||||||
if pointerKind != reflect.Map {
|
if pointerKind != reflect.Map {
|
||||||
return gerror.Newf("pointer should be type of *map, but got:%s", pointerKind)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "pointer should be type of *map, but got:%s", pointerKind)
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
// Catch the panic, especially the reflect operation panics.
|
// Catch the panic, especially the reflect operation panics.
|
||||||
@ -94,7 +94,7 @@ func doMapToMap(params interface{}, pointer interface{}, mapping ...map[string]s
|
|||||||
if e, ok := exception.(errorStack); ok {
|
if e, ok := exception.(errorStack); ok {
|
||||||
err = e
|
err = e
|
||||||
} else {
|
} else {
|
||||||
err = gerror.NewSkipf(1, "%v", exception)
|
err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
@ -73,7 +73,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]
|
|||||||
paramsKind = paramsRv.Kind()
|
paramsKind = paramsRv.Kind()
|
||||||
}
|
}
|
||||||
if paramsKind != reflect.Array && paramsKind != reflect.Slice {
|
if paramsKind != reflect.Array && paramsKind != reflect.Slice {
|
||||||
return gerror.New("params should be type of slice, eg: []map/[]*map/[]struct/[]*struct")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "params should be type of slice, eg: []map/[]*map/[]struct/[]*struct")
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
paramsElem = paramsRv.Type().Elem()
|
paramsElem = paramsRv.Type().Elem()
|
||||||
@ -84,7 +84,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]
|
|||||||
paramsElemKind = paramsElem.Kind()
|
paramsElemKind = paramsElem.Kind()
|
||||||
}
|
}
|
||||||
if paramsElemKind != reflect.Map && paramsElemKind != reflect.Struct && paramsElemKind != reflect.Interface {
|
if paramsElemKind != reflect.Map && paramsElemKind != reflect.Struct && paramsElemKind != reflect.Interface {
|
||||||
return gerror.Newf("params element should be type of map/*map/struct/*struct, but got: %s", paramsElemKind)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "params element should be type of map/*map/struct/*struct, but got: %s", paramsElemKind)
|
||||||
}
|
}
|
||||||
// Empty slice, no need continue.
|
// Empty slice, no need continue.
|
||||||
if paramsRv.Len() == 0 {
|
if paramsRv.Len() == 0 {
|
||||||
@ -100,7 +100,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]
|
|||||||
pointerKind = pointerRv.Kind()
|
pointerKind = pointerRv.Kind()
|
||||||
}
|
}
|
||||||
if pointerKind != reflect.Array && pointerKind != reflect.Slice {
|
if pointerKind != reflect.Array && pointerKind != reflect.Slice {
|
||||||
return gerror.New("pointer should be type of *[]map/*[]*map")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "pointer should be type of *[]map/*[]*map")
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
pointerElemType = pointerRv.Type().Elem()
|
pointerElemType = pointerRv.Type().Elem()
|
||||||
@ -110,7 +110,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]
|
|||||||
pointerElemKind = pointerElemType.Elem().Kind()
|
pointerElemKind = pointerElemType.Elem().Kind()
|
||||||
}
|
}
|
||||||
if pointerElemKind != reflect.Map {
|
if pointerElemKind != reflect.Map {
|
||||||
return gerror.New("pointer element should be type of map/*map")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "pointer element should be type of map/*map")
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
// Catch the panic, especially the reflect operation panics.
|
// Catch the panic, especially the reflect operation panics.
|
||||||
@ -118,7 +118,7 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]
|
|||||||
if e, ok := exception.(errorStack); ok {
|
if e, ok := exception.(errorStack); ok {
|
||||||
err = e
|
err = e
|
||||||
} else {
|
} else {
|
||||||
err = gerror.NewSkipf(1, "%v", exception)
|
err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
@ -23,7 +23,7 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string)
|
|||||||
pointerKind = pointerType.Kind()
|
pointerKind = pointerType.Kind()
|
||||||
)
|
)
|
||||||
if pointerKind != reflect.Ptr {
|
if pointerKind != reflect.Ptr {
|
||||||
return gerror.Newf("params should be type of pointer, but got: %v", pointerKind)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "params should be type of pointer, but got: %v", pointerKind)
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
pointerElem = pointerType.Elem()
|
pointerElem = pointerType.Elem()
|
||||||
@ -60,7 +60,7 @@ func ScanDeep(params interface{}, pointer interface{}, mapping ...map[string]str
|
|||||||
t := reflect.TypeOf(pointer)
|
t := reflect.TypeOf(pointer)
|
||||||
k := t.Kind()
|
k := t.Kind()
|
||||||
if k != reflect.Ptr {
|
if k != reflect.Ptr {
|
||||||
return gerror.Newf("params should be type of pointer, but got: %v", k)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "params should be type of pointer, but got: %v", k)
|
||||||
}
|
}
|
||||||
switch t.Elem().Kind() {
|
switch t.Elem().Kind() {
|
||||||
case reflect.Array, reflect.Slice:
|
case reflect.Array, reflect.Slice:
|
||||||
|
@ -7,7 +7,6 @@
|
|||||||
package gconv
|
package gconv
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"github.com/gogf/gf/errors/gerror"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"github.com/gogf/gf/internal/empty"
|
"github.com/gogf/gf/internal/empty"
|
||||||
"github.com/gogf/gf/internal/json"
|
"github.com/gogf/gf/internal/json"
|
||||||
@ -63,7 +62,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if pointer == nil {
|
if pointer == nil {
|
||||||
return gerror.New("object pointer cannot be nil")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
@ -72,7 +71,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
|||||||
if e, ok := exception.(errorStack); ok {
|
if e, ok := exception.(errorStack); ok {
|
||||||
err = e
|
err = e
|
||||||
} else {
|
} else {
|
||||||
err = gerror.NewSkipf(1, "%v", exception)
|
err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@ -125,11 +124,11 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
|||||||
pointerReflectValue = reflect.ValueOf(pointer)
|
pointerReflectValue = reflect.ValueOf(pointer)
|
||||||
pointerReflectKind = pointerReflectValue.Kind()
|
pointerReflectKind = pointerReflectValue.Kind()
|
||||||
if pointerReflectKind != reflect.Ptr {
|
if pointerReflectKind != reflect.Ptr {
|
||||||
return gerror.Newf("object pointer should be type of '*struct', but got '%v'", pointerReflectKind)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "object pointer should be type of '*struct', but got '%v'", pointerReflectKind)
|
||||||
}
|
}
|
||||||
// Using IsNil on reflect.Ptr variable is OK.
|
// Using IsNil on reflect.Ptr variable is OK.
|
||||||
if !pointerReflectValue.IsValid() || pointerReflectValue.IsNil() {
|
if !pointerReflectValue.IsValid() || pointerReflectValue.IsNil() {
|
||||||
return gerror.New("object pointer cannot be nil")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil")
|
||||||
}
|
}
|
||||||
pointerElemReflectValue = pointerReflectValue.Elem()
|
pointerElemReflectValue = pointerReflectValue.Elem()
|
||||||
}
|
}
|
||||||
@ -167,7 +166,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
|||||||
// DO NOT use MapDeep here.
|
// DO NOT use MapDeep here.
|
||||||
paramsMap := Map(paramsInterface)
|
paramsMap := Map(paramsInterface)
|
||||||
if paramsMap == nil {
|
if paramsMap == nil {
|
||||||
return gerror.Newf("convert params to map failed: %v", params)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "convert params to map failed: %v", params)
|
||||||
}
|
}
|
||||||
|
|
||||||
// It only performs one converting to the same attribute.
|
// It only performs one converting to the same attribute.
|
||||||
@ -308,7 +307,7 @@ func bindVarToStructAttr(elem reflect.Value, name string, value interface{}, map
|
|||||||
defer func() {
|
defer func() {
|
||||||
if exception := recover(); exception != nil {
|
if exception := recover(); exception != nil {
|
||||||
if err = bindVarToReflectValue(structFieldValue, value, mapping, priorityTag); err != nil {
|
if err = bindVarToReflectValue(structFieldValue, value, mapping, priorityTag); err != nil {
|
||||||
err = gerror.Wrapf(err, `error binding value to attribute "%s"`, name)
|
err = gerror.WrapCodef(gerror.CodeInternalError, err, `error binding value to attribute "%s"`, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@ -461,12 +460,12 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}, ma
|
|||||||
default:
|
default:
|
||||||
defer func() {
|
defer func() {
|
||||||
if exception := recover(); exception != nil {
|
if exception := recover(); exception != nil {
|
||||||
err = gerror.New(
|
err = gerror.NewCodef(
|
||||||
fmt.Sprintf(`cannot convert value "%+v" to type "%s":%+v`,
|
gerror.CodeInternalError,
|
||||||
|
`cannot convert value "%+v" to type "%s":%+v`,
|
||||||
value,
|
value,
|
||||||
structFieldValue.Type().String(),
|
structFieldValue.Type().String(),
|
||||||
exception,
|
exception,
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
@ -51,7 +51,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if pointer == nil {
|
if pointer == nil {
|
||||||
return gerror.New("object pointer cannot be nil")
|
return gerror.NewCode(gerror.CodeInvalidParameter, "object pointer cannot be nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
if doStructsByDirectReflectSet(params, pointer) {
|
if doStructsByDirectReflectSet(params, pointer) {
|
||||||
@ -64,7 +64,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin
|
|||||||
if e, ok := exception.(errorStack); ok {
|
if e, ok := exception.(errorStack); ok {
|
||||||
err = e
|
err = e
|
||||||
} else {
|
} else {
|
||||||
err = gerror.NewSkipf(1, "%v", exception)
|
err = gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@ -96,7 +96,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin
|
|||||||
if !ok {
|
if !ok {
|
||||||
pointerRv = reflect.ValueOf(pointer)
|
pointerRv = reflect.ValueOf(pointer)
|
||||||
if kind := pointerRv.Kind(); kind != reflect.Ptr {
|
if kind := pointerRv.Kind(); kind != reflect.Ptr {
|
||||||
return gerror.Newf("pointer should be type of pointer, but got: %v", kind)
|
return gerror.NewCodef(gerror.CodeInvalidParameter, "pointer should be type of pointer, but got: %v", kind)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Converting `params` to map slice.
|
// Converting `params` to map slice.
|
||||||
|
@ -7,7 +7,7 @@
|
|||||||
package gvalid
|
package gvalid
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"github.com/gogf/gf/text/gregex"
|
"github.com/gogf/gf/text/gregex"
|
||||||
"github.com/gogf/gf/text/gstr"
|
"github.com/gogf/gf/text/gstr"
|
||||||
"strings"
|
"strings"
|
||||||
@ -15,6 +15,7 @@ import (
|
|||||||
|
|
||||||
// Error is the validation error for validation result.
|
// Error is the validation error for validation result.
|
||||||
type Error interface {
|
type Error interface {
|
||||||
|
Code() int
|
||||||
Current() error
|
Current() error
|
||||||
Error() string
|
Error() string
|
||||||
FirstItem() (key string, messages map[string]string)
|
FirstItem() (key string, messages map[string]string)
|
||||||
@ -29,6 +30,7 @@ type Error interface {
|
|||||||
|
|
||||||
// validationError is the validation error for validation result.
|
// validationError is the validation error for validation result.
|
||||||
type validationError struct {
|
type validationError struct {
|
||||||
|
code int // Error code.
|
||||||
rules []string // Rules by sequence, which is used for keeping error sequence.
|
rules []string // Rules by sequence, which is used for keeping error sequence.
|
||||||
errors map[string]map[string]string // Error map:map[field]map[rule]message
|
errors map[string]map[string]string // Error map:map[field]map[rule]message
|
||||||
firstKey string // The first error rule key(empty in default).
|
firstKey string // The first error rule key(empty in default).
|
||||||
@ -36,7 +38,7 @@ type validationError struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newError creates and returns a validation error.
|
// newError creates and returns a validation error.
|
||||||
func newError(rules []string, errors map[string]map[string]string) *validationError {
|
func newError(code int, rules []string, errors map[string]map[string]string) *validationError {
|
||||||
for field, m := range errors {
|
for field, m := range errors {
|
||||||
for k, v := range m {
|
for k, v := range m {
|
||||||
v = strings.Replace(v, ":attribute", field, -1)
|
v = strings.Replace(v, ":attribute", field, -1)
|
||||||
@ -47,6 +49,7 @@ func newError(rules []string, errors map[string]map[string]string) *validationEr
|
|||||||
errors[field] = m
|
errors[field] = m
|
||||||
}
|
}
|
||||||
return &validationError{
|
return &validationError{
|
||||||
|
code: code,
|
||||||
rules: rules,
|
rules: rules,
|
||||||
errors: errors,
|
errors: errors,
|
||||||
}
|
}
|
||||||
@ -54,13 +57,21 @@ func newError(rules []string, errors map[string]map[string]string) *validationEr
|
|||||||
|
|
||||||
// newErrorStr creates and returns a validation error by string.
|
// newErrorStr creates and returns a validation error by string.
|
||||||
func newErrorStr(key, err string) *validationError {
|
func newErrorStr(key, err string) *validationError {
|
||||||
return newError(nil, map[string]map[string]string{
|
return newError(gerror.CodeInternalError, nil, map[string]map[string]string{
|
||||||
internalErrorMapKey: {
|
internalErrorMapKey: {
|
||||||
key: err,
|
key: err,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Code returns the error code of current validation error.
|
||||||
|
func (e *validationError) Code() int {
|
||||||
|
if e == nil {
|
||||||
|
return gerror.CodeNil
|
||||||
|
}
|
||||||
|
return e.code
|
||||||
|
}
|
||||||
|
|
||||||
// Map returns the first error message as map.
|
// Map returns the first error message as map.
|
||||||
func (e *validationError) Map() map[string]string {
|
func (e *validationError) Map() map[string]string {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
@ -179,7 +190,7 @@ func (e *validationError) Current() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
_, err := e.FirstRule()
|
_, err := e.FirstRule()
|
||||||
return errors.New(err)
|
return gerror.NewCode(e.code, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// String returns all error messages as string, multiple error messages joined using char ';'.
|
// String returns all error messages as string, multiple error messages joined using char ';'.
|
||||||
|
@ -7,6 +7,7 @@
|
|||||||
package gvalid
|
package gvalid
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"github.com/gogf/gf/util/gconv"
|
"github.com/gogf/gf/util/gconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@ -130,7 +131,7 @@ func (v *Validator) doCheckMap(params interface{}) Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(errorMaps) > 0 {
|
if len(errorMaps) > 0 {
|
||||||
return newError(errorRules, errorMaps)
|
return newError(gerror.CodeValidationFailed, errorRules, errorMaps)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@
|
|||||||
package gvalid
|
package gvalid
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"github.com/gogf/gf/internal/structs"
|
"github.com/gogf/gf/internal/structs"
|
||||||
"github.com/gogf/gf/util/gconv"
|
"github.com/gogf/gf/util/gconv"
|
||||||
"github.com/gogf/gf/util/gutil"
|
"github.com/gogf/gf/util/gutil"
|
||||||
@ -249,7 +250,7 @@ func (v *Validator) doCheckStruct(object interface{}) Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(errorMaps) > 0 {
|
if len(errorMaps) > 0 {
|
||||||
return newError(errorRules, errorMaps)
|
return newError(gerror.CodeValidationFailed, errorRules, errorMaps)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@
|
|||||||
package gvalid
|
package gvalid
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"github.com/gogf/gf/errors/gerror"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@ -138,7 +138,7 @@ func (v *Validator) doCheckValue(
|
|||||||
index++
|
index++
|
||||||
}
|
}
|
||||||
if len(errorMsgArray) > 0 {
|
if len(errorMsgArray) > 0 {
|
||||||
return newError([]string{rules}, map[string]map[string]string{
|
return newError(gerror.CodeValidationFailed, []string{rules}, map[string]map[string]string{
|
||||||
key: errorMsgArray,
|
key: errorMsgArray,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -175,7 +175,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
"max-length",
|
"max-length",
|
||||||
"size":
|
"size":
|
||||||
if msg := v.checkLength(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
|
if msg := v.checkLength(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
|
||||||
return match, errors.New(msg)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: msg,
|
||||||
|
Code: gerror.CodeValidationFailed,
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
match = true
|
match = true
|
||||||
}
|
}
|
||||||
@ -186,7 +189,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
"max",
|
"max",
|
||||||
"between":
|
"between":
|
||||||
if msg := v.checkRange(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
|
if msg := v.checkRange(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
|
||||||
return match, errors.New(msg)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: msg,
|
||||||
|
Code: gerror.CodeValidationFailed,
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
match = true
|
match = true
|
||||||
}
|
}
|
||||||
@ -222,7 +228,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
var msg string
|
var msg string
|
||||||
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
||||||
msg = strings.Replace(msg, ":format", rulePattern, -1)
|
msg = strings.Replace(msg, ":format", rulePattern, -1)
|
||||||
return match, errors.New(msg)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: msg,
|
||||||
|
Code: gerror.CodeValidationFailed,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Values of two fields should be equal as string.
|
// Values of two fields should be equal as string.
|
||||||
@ -237,7 +246,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
var msg string
|
var msg string
|
||||||
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
||||||
msg = strings.Replace(msg, ":field", rulePattern, -1)
|
msg = strings.Replace(msg, ":field", rulePattern, -1)
|
||||||
return match, errors.New(msg)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: msg,
|
||||||
|
Code: gerror.CodeValidationFailed,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Values of two fields should not be equal as string.
|
// Values of two fields should not be equal as string.
|
||||||
@ -253,7 +265,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
var msg string
|
var msg string
|
||||||
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
msg = v.getErrorMessageByRule(ruleKey, customMsgMap)
|
||||||
msg = strings.Replace(msg, ":field", rulePattern, -1)
|
msg = strings.Replace(msg, ":field", rulePattern, -1)
|
||||||
return match, errors.New(msg)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: msg,
|
||||||
|
Code: gerror.CodeValidationFailed,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Field value should be in range of.
|
// Field value should be in range of.
|
||||||
@ -436,7 +451,10 @@ func (v *Validator) doCheckBuildInRules(
|
|||||||
match = gregex.IsMatchString(`^([0-9A-Fa-f]{2}[\-:]){5}[0-9A-Fa-f]{2}$`, valueStr)
|
match = gregex.IsMatchString(`^([0-9A-Fa-f]{2}[\-:]){5}[0-9A-Fa-f]{2}$`, valueStr)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return match, errors.New("Invalid rule name: " + ruleKey)
|
return match, gerror.NewOption(gerror.Option{
|
||||||
|
Text: "Invalid rule name: " + ruleKey,
|
||||||
|
Code: gerror.CodeInvalidParameter,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return match, nil
|
return match, nil
|
||||||
}
|
}
|
||||||
|
@ -1014,3 +1014,16 @@ func Test_InternalError_String(t *testing.T) {
|
|||||||
t.Assert(gerror.Current(err), "InvalidRules: hh")
|
t.Assert(gerror.Current(err), "InvalidRules: hh")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user