目錄
- 前言
- 用戶自定義類型
- 上下文數(shù)據(jù)
- 原因(Causes)
- 組件(Component)
- 響應(yīng)類型(ResponseType)
- 重試
- GoError 接口
- 抽象error
- 結(jié)論
前言
Go語言很強大并且現(xiàn)在也十分流行 — 許多項目都是用Go語言來實現(xiàn)的,如Kubernetes。Go語言的一個有趣特性是它的多值返回功能提供了一種與其他編程語言不同的錯誤處理方法。 Go將error視為具有預(yù)定義類型的值,其本身是一個interface類型。然而,編寫多層體系結(jié)構(gòu)應(yīng)用程序并使用api暴露應(yīng)用的特性需要有包含更多上下文信息的error處理,而不僅僅是一個值。 本文我們將探討如何封裝Go的error類型以在應(yīng)用程序中帶來更大的價值。
用戶自定義類型
我們將重寫的Go里自帶的error類型,首先從一個自定義的錯誤類型開始,該錯誤類型將在程序中識別為error類型。因此,我們引入一個封裝了Go的 error的新自定義Error類型。
type GoError struct {
error
}
上下文數(shù)據(jù)
當我們在Go中說error是一個值時,它是字符串值 - 任何實現(xiàn)了Error() string函數(shù)的類型都可以視作error類型。將字符串值視為error會使跨層的error處理復(fù)雜化,因此處理error字符串信息并不是正確的方法。所以我們可以把字符串和錯誤碼解耦:
type GoError struct {
error
Code string
}
現(xiàn)在對error的處理將基于錯誤碼Code字段而不是字符串。讓我們通過上下文數(shù)據(jù)進一步對錯誤字符串進行解耦,在上下文數(shù)據(jù)中可以使用i18n包進行國際化。
type GoError struct {
error
Code string
Data map[string]interface{}
}
Data包含用于構(gòu)造錯誤字符串的上下文數(shù)據(jù)。錯誤字符串可以通過數(shù)據(jù)模板化:
//i18N def
"InvalidParamValue": "Invalid parameter value '{{.actual}}', expected '{{.expected}}' for '{{.name}}'"
在i18N定義文件中,錯誤碼Code將會映射到使用Data構(gòu)建的模板化的錯誤字符串中。
原因(Causes)
error可能發(fā)生在任何一層,有必要為每一層提供處理error的選項,并在不丟失原始error值的情況下進一步使用附加的上下文信息對error進行包裝。GoError結(jié)構(gòu)體可以用Causes進一步封裝,用來保存整個錯誤堆棧。
type GoError struct {
error
Code string
Data map[string]interface{}
Causes []error
}
如果必須保存多個error數(shù)據(jù),則causes是一個數(shù)組類型,并將其設(shè)置為基本error類型,以便在程序中包含該原因的第三方錯誤。
組件(Component)
標記層組件將有助于識別error發(fā)生在哪一層,并且可以避免不必要的error wrap。例如,如果service類型的error組件發(fā)生在服務(wù)層,則可能不需要wrap error。檢查組件信息將有助于防止暴露給用戶不應(yīng)該通知的error,比如數(shù)據(jù)庫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"
)
響應(yīng)類型(ResponseType)
添加一個錯誤響應(yīng)類型這樣可以支持error分類,以便于了解什么錯誤類型。例如,可以根據(jù)響應(yīng)類型(如NotFound)對error進行分類,像DbRecordNotFound、ResourceNotFound、UserNotFound等等的error都可以歸類為 NotFound error。這在多層應(yīng)用程序開發(fā)過程中非常有用,而且是可選的封裝:
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"
)
重試
在少數(shù)情況下,出現(xiàn)error會進行重試。retry字段可以通過設(shè)置Retryable標記來決定是否要進行error重試:
type GoError struct {
error
Code string
Message string
Data map[string]interface{}
Causes []error
Component ErrComponent
ResponseType ResponseErrType
Retryable bool
}
GoError 接口
通過定義一個帶有GoError實現(xiàn)的顯式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函數(shù)的可重用性
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函數(shù)抽象了ResourceNotFound這個error,開發(fā)者可以使用這個函數(shù)來返回error對象而不是每次創(chuàng)建一個新的對象:
//UserService
user, err := u.repo.FindUser(ctx, userId)
if err != nil {
if err.ResponseType == NotFound {
return ResourceNotFound(userUid, "User", err)
}
return err
}
結(jié)論
我們演示了如何使用添加上下文數(shù)據(jù)的自定義Go的error類型,從而使得error在多層應(yīng)用程序中更有意義。你可以在這里[1]看到完整的代碼實現(xiàn)和定義。
到此這篇關(guān)于Go應(yīng)用中優(yōu)雅處理Error的文章就介紹到這了,更多相關(guān)Go優(yōu)雅處理Error內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
參考資料
[1] 這里: https://gist.github.com/prathabk/744367cbfc70435c56956f650612d64b
您可能感興趣的文章:- GO語言標準錯誤處理機制error用法實例
- Go 自定義error錯誤的處理方法
- golang 打印error的堆棧信息操作
- 淺談Go語言的error類型
- 淺析golang開發(fā)Error的使用詳解