Go 中的 error 居然可以這樣封裝
本文由周浩翻譯自:https://medium.com/spectro-cloud/decorating-go-error-d1db60bb9249,ironbox 和 Tang Ruilin 參與校對。
Go 語言很強大並且現在也十分流行 — 許多項目都是用 Go 語言來實現的,如 Kubernetes。Go 語言的一個有趣特性是它的多值返回功能提供了一種與其他編程語言不同的錯誤處理方法。 Go 將 error 視爲具有預定義類型的值,其本身是一個 interface 類型。然而,編寫多層體系結構應用程序並使用 api 暴露應用的特性需要有包含更多上下文信息的 error 處理,而不僅僅是一個值。 本文我們將探討如何封裝 Go 的 error 類型以在應用程序中帶來更大的價值。
用戶自定義類型
我們將重寫的 Go 裏自帶的error
類型,首先從一個自定義的錯誤類型開始,該錯誤類型將在程序中識別爲error
類型。因此,我們引入一個封裝了 Go 的 error
的新自定義 Error 類型。
type GoError struct {
error
}
上下文數據
當我們在 Go 中說 error 是一個值時,它是字符串值 - 任何實現了Error() string
函數的類型都可以視作 error 類型。將字符串值視爲 error 會使跨層的 error 處理複雜化,因此處理 error 字符串信息並不是正確的方法。所以我們可以把字符串和錯誤碼解耦:
type GoError struct {
error
Code string
}
現在對 error 的處理將基於錯誤碼Code
字段而不是字符串。讓我們通過上下文數據進一步對錯誤字符串進行解耦,在上下文數據中可以使用i18n
包進行國際化。
type GoError struct {
error
Code string
Data map[string]interface{}
}
Data
包含用於構造錯誤字符串的上下文數據。錯誤字符串可以通過數據模板化:
//i18N def
"InvalidParamValue": "Invalid parameter value '{{.actual}}', expected '{{.expected}}' for '{{.name}}'"
在 i18N 定義文件中,錯誤碼Code
將會映射到使用Data
構建的模板化的錯誤字符串中。
原因 (Causes)
error 可能發生在任何一層,有必要爲每一層提供處理 error 的選項,並在不丟失原始 error 值的情況下進一步使用附加的上下文信息對 error 進行包裝。GoError
結構體可以用Causes
進一步封裝,用來保存整個錯誤堆棧。
type GoError struct {
error
Code string
Data map[string]interface{}
Causes []error
}
如果必須保存多個 error 數據,則causes
是一個數組類型,並將其設置爲基本error
類型,以便在程序中包含該原因的第三方錯誤。
組件 (Component)
標記層組件將有助於識別 error 發生在哪一層,並且可以避免不必要的 error wrap。例如,如果service
類型的 error 組件發生在服務層,則可能不需要 wrap error。檢查組件信息將有助於防止暴露給用戶不應該通知的 error,比如數據庫 error:
type GoError struct {
error
Code string
Data map[string]interface{}
Causes []error
Component ErrComponent
}
type ErrComponent string
const (
ErrService ErrComponent = "service"
ErrRepo ErrComponent = "repository"
ErrLib ErrComponent = "library"
)
響應類型 (ResponseType)
添加一個錯誤響應類型這樣可以支持 error 分類,以便於瞭解什麼錯誤類型。例如,可以根據響應類型 (如NotFound
) 對 error 進行分類,像DbRecordNotFound
、ResourceNotFound
、UserNotFound
等等的 error 都可以歸類爲 NotFound
error。這在多層應用程序開發過程中非常有用,而且是可選的封裝:
type GoError struct {
error
Code string
Data map[string]interface{}
Causes []error
Component ErrComponent
ResponseType ResponseErrType
}
type ResponseErrType string
const (
BadRequest ResponseErrType = "BadRequest"
Forbidden ResponseErrType = "Forbidden"
NotFound ResponseErrType = "NotFound"
AlreadyExists ResponseErrType = "AlreadyExists"
)
重試
在少數情況下,出現 error 會進行重試。retry 字段可以通過設置Retryable
標記來決定是否要進行 error 重試:
type GoError struct {
error
Code string
Message string
Data map[string]interface{}
Causes []error
Component ErrComponent
ResponseType ResponseErrType
Retryable bool
}
GoError 接口
通過定義一個帶有GoError
實現的顯式 error 接口,可以簡化 error 檢查:
package goerr
type Error interface {
error
Code() string
Message() string
Cause() error
Causes() []error
Data() map[string]interface{}
String() string
ResponseErrType() ResponseErrType
SetResponseType(r ResponseErrType) Error
Component() ErrComponent
SetComponent(c ErrComponent) Error
Retryable() bool
SetRetryable() Error
}
抽象 error
有了上述的封裝方式,更重要的是對 error 進行抽象,將這些封裝保存在同一地方,並提供 error 函數的可重用性
func ResourceNotFound(id, kind string, cause error) GoError {
data := map[string]interface{}{"kind": kind, "id": id}
return GoError{
Code: "ResourceNotFound",
Data: data,
Causes: []error{cause},
Component: ErrService,
ResponseType: NotFound,
Retryable: false,
}
}
這個 error 函數抽象了ResourceNotFound
這個 error,開發者可以使用這個函數來返回 error 對象而不是每次創建一個新的對象:
//UserService
user, err := u.repo.FindUser(ctx, userId)
if err != nil {
if err.ResponseType == NotFound {
return ResourceNotFound(userUid, "User", err)
}
return err
}
結論
我們演示瞭如何使用添加上下文數據的自定義 Go 的 error 類型,從而使得 error 在多層應用程序中更有意義。你可以在這裏 [1] 看到完整的代碼實現和定義。
參考資料
[1]
這裏: https://gist.github.com/prathabk/744367cbfc70435c56956f650612d64b
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/q2VrY8ksNsmYzvqhUNv72A