forked from betty200744/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror_handling.go
55 lines (46 loc) · 1.16 KB
/
error_handling.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package error_handling
import (
"errors"
"reflect"
)
// ---------------
// variables Error
// ---------------
var (
ErrArgs = errors.New("args error")
)
func WebCall2() error {
return ErrArgs
}
// ---------------
// default Error
// ---------------
func WebCall1() error {
return errors.New("default error")
}
// ---------------
// Type as context, Custom Error
// ---------------
type UnmarshalTypeError struct {
Value string // description of JSON value
Type reflect.Type // type of Go value it could not be assigned to
}
func (e *UnmarshalTypeError) Error() string {
return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
}
type InvalidUnmarshalError struct {
Type reflect.Type
}
func (e *InvalidUnmarshalError) Error() string {
if e.Type.Kind() != reflect.Ptr {
return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "json: Unmarshal(nil " + e.Type.String() + ")"
}
func Unmarshal(data []byte, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(v)}
}
return &UnmarshalTypeError{"string", reflect.TypeOf(v)}
}