改之前
在使用 gin 開發介面的時候,回傳介面資料是這樣寫的,
type response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// always return http.StatusOK
c.JSON(http.StatusOK, response{
Code: 20101,
Msg: "用戶手機號不合法",
Data: nil,
})
這種寫法 code、msg 都是在哪需要回傳在哪定義,沒有進行統一管理,
改之后
// 比如,回傳“用戶手機號不合法”錯誤
c.JSON(http.StatusOK, errno.ErrUserPhone.WithID(c.GetString("trace-id")))
// 正確回傳
c.JSON(http.StatusOK, errno.OK.WithData(data).WithID(c.GetString("trace-id")))
errno.ErrUserPhone、errno.OK 表示自定義的錯誤碼,下面會看到定義的地方,
.WithID() 設定當前請求的唯一ID,也可以理解為鏈路ID,忽略也可以,
.WithData() 設定成功時回傳的資料,
下面分享下撰寫的 errno 包原始碼,非常簡單,希望大家不要介意,
errno 包原始碼
// errno/errno.go
package errno
import (
"encoding/json"
)
var _ Error = (*err)(nil)
type Error interface {
// i 為了避免被其他包實作
i()
// WithData 設定成功時回傳的資料
WithData(data interface{}) Error
// WithID 設定當前請求的唯一ID
WithID(id string) Error
// ToString 回傳 JSON 格式的錯誤詳情
ToString() string
}
type err struct {
Code int `json:"code"` // 業務編碼
Msg string `json:"msg"` // 錯誤描述
Data interface{} `json:"data"` // 成功時回傳的資料
ID string `json:"id,omitempty"` // 當前請求的唯一ID,便于問題定位,忽略也可以
}
func NewError(code int, msg string) Error {
return &err{
Code: code,
Msg: msg,
Data: nil,
}
}
func (e *err) i() {}
func (e *err) WithData(data interface{}) Error {
e.Data = https://www.cnblogs.com/xinliangcoder/p/data
return e
}
func (e *err) WithID(id string) Error {
e.ID = id
return e
}
// ToString 回傳 JSON 格式的錯誤詳情
func (e *err) ToString() string {
err := &struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
ID string `json:"id,omitempty"`
}{
Code: e.Code,
Msg: e.Msg,
Data: e.Data,
ID: e.ID,
}
raw, _ := json.Marshal(err)
return string(raw)
}
// errno/code.go
package errno
var (
// OK
OK = NewError(0, "OK")
// 服務級錯誤碼
ErrServer = NewError(10001, "服務例外,請聯系管理員")
ErrParam = NewError(10002, "引數有誤")
ErrSignParam = NewError(10003, "簽名引數有誤")
// 模塊級錯誤碼 - 用戶模塊
ErrUserPhone = NewError(20101, "用戶手機號不合法")
ErrUserCaptcha = NewError(20102, "用戶驗證碼有誤")
// ...
)
錯誤碼規則
- 錯誤碼需在
code.go檔案中定義, - 錯誤碼需為 > 0 的數,反之表示正確,
錯誤碼為 5 位數
| 1 | 01 | 01 |
|---|---|---|
| 服務級錯誤碼 | 模塊級錯誤碼 | 具體錯誤碼 |
- 服務級別錯誤碼:1 位數進行表示,比如 1 為系統級錯誤;2 為普通錯誤,通常是由用戶非法操作引起,
- 模塊級錯誤碼:2 位數進行表示,比如 01 為用戶模塊;02 為訂單模塊,
- 具體錯誤碼:2 位數進行表示,比如 01 為手機號不合法;02 為驗證碼輸入錯誤,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/241196.html
標籤:Go
上一篇:[系列] Go - 學習 grpc.Dial(target string, opts …DialOption) 的寫法
下一篇:Go操作Redis實戰
