Day10(接口和错误处理)
interface And Panic、Error
interface
接口创建使用
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"github.com/Cc360428/HelpPackage/UtilsHelp/logs"
"github.com/pkg/errors"
)
// UserInterface
type UserInterface interface {
Add(User) error
Get(int) (User, error)
Delete(int) error
Update(User) error
List(int, int) ([]User, int, error)
}
// User
type User struct {
Id int
Name string
Age int
}
// 获取
func (u *User) Get(id int) (user User, err error) {
if id == 0 {
return user, errors.New("id not")
}
user.Age = 18
user.Name = "Get"
user.Id = id
return
}
// Add
func (u *User) Add(user User) error {
return nil
}
// 删除
func (u *User) Delete(id int) error {
return nil
}
// 添加
func (u *User) Update(user User) error {
return nil
}
// 列表
func (u *User) List(l, o int) (list []User, total int, err error) {
return
}
func main() {
var userInterface UserInterface
userInterface = new(User)
user, err := userInterface.Get(1)
if err != nil {
logs.Error(err.Error())
return
}
logs.Info(user)
u := new(User)
ue, err := u.Get(0)
if err != nil {
logs.Error(err.Error())
return
}
logs.Info(ue)
}
1
2
2020/04/25 17:55:05.333 [I] [day10.go:63] {1 Get 18}
2020/04/25 17:55:05.369 [E] [day10.go:67] id not
Panic、Error
Panic
recover()
捕捉程序终止异常,正常的打印捕捉异常,可以试试 把defer func(){}()
代码注释,会不会打印usr defer
,程序会自动将整个程序全部停止
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
package main
import (
"github.com/Cc360428/HelpPackage/UtilsHelp/logs"
"runtime"
)
func AddressOrNil(f func()) {
defer func() {
if r := recover(); r != nil {
switch r.(type) {
case runtime.Error: // 运行时错误
logs.Info("runtime error:", r)
default: // 非运行时错误
logs.Info("error:", r)
}
}
}()
f()
}
func main() {
AddressOrNil(func() {
var a *struct{ Name string }
a.Name = "Cc"
})
logs.Info("usr defer ")
}
1
2
2020/04/25 18:24:27.623 [I] [panic.go:13] runtime error: runtime error: invalid memory address or nil pointer dereference
2020/04/25 18:24:27.661 [I] [panic.go:28] usr defer
error
程序中错误处理 大致分两大类:
panic
会造成程序终止 ,error
程序错误,或者自定义的业务逻辑不合法抛出异常
- 自定义方法一定业务逻辑返回
error
这个返回值是在最后一个(习惯)
This post is licensed under
CC BY 4.0
by the author.