0%

beego-error处理模板

baseController.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
package phone

import (
"github.com/astaxie/beego"
)


type BaseController struct {
beego.Controller
}

func (this *BaseController)Prepare(){
if this.GetString("key") != KEY {
this.RetError(CreateError(KEY_ERROR,nil))
}
}

func (this *BaseController)CheckString(strs... string) {
for _,str := range strs {
if str == ""{
this.RetError(CreateError(PARAM_IS_NULL,nil))
}
}
}

func (this *BaseController)RetSuccess(data interface{}) {
result := CreateSuccess(data)
this.Data["json"] = result
this.ServeJSON()
this.StopRun()
}

func (this *BaseController)RetError(myError *MyError) {
this.Data["json"] = myError
this.ServeJSON()
this.StopRun()
}

error.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
package phone

import (
"errors"
"github.com/astaxie/beego"
"runtime/debug"
)

type MyError struct {
Code string `json:"code"`
Desc string `json:"desc"`
Data interface{} `json:"data"`
Debug string `json:"debug"`
Err string `json:"error"`
}

func (this MyError) Error() string {
return this.Err
}

// 创建error
func CreateError(myError *MyError,err error) *MyError {
if err == nil {
err = errors.New("未填写error")
}

if beego.AppConfig.String("runmode") == "dev" {
myError.Data = ""
myError.Err = err.Error()
}

myError.Debug = string(debug.Stack())
return myError
}

func CreateSuccess(data interface{}) *MyError {
if data == nil {
data = ""
}
return &MyError{Code:"0000",Desc:"操作成功",Data:data,Err:""}
}

var KEY_ERROR = &MyError{Code:"0001",Desc:"鉴权key值校验失败"}
var NOT_FOUND_DEVICE_BY_SN = &MyError{Code:"0002",Desc:"通过SN未查询到设备"}
var PARAM_IS_NULL = &MyError{Code:"0003",Desc:"必传参数为空"}