一篇聊聊Go錯誤封裝機(jī)制
作者:浩仔浩仔
使用 %w 時,它會在格式化字符串中占據(jù)一個位置,并將其后的錯誤作為參數(shù)傳遞給 fmt.Errorf 或 fmt.Sprintf 函數(shù)。這將創(chuàng)建一個新的錯誤,包含了原始錯誤信息,并形成一個錯誤鏈。
%w 是用于錯誤包裝(Error Wrapping)的格式化動詞。它是用于 fmt.Errorf 和 fmt.Sprintf 函數(shù)中的一個特殊格式化動詞,用于將一個錯誤(或其他可打印的值)包裝在一個新的錯誤中。
使用 %w 時,它會在格式化字符串中占據(jù)一個位置,并將其后的錯誤作為參數(shù)傳遞給 fmt.Errorf 或 fmt.Sprintf 函數(shù)。這將創(chuàng)建一個新的錯誤,包含了原始錯誤信息,并形成一個錯誤鏈。
下面是一個示例,展示了如何使用 %w 來進(jìn)行錯誤包裝:
package main
import (
"errors"
"fmt"
)
func doSomething() error {
return errors.New("something went wrong")
}
func main() {
err := doSomething()
// Wrap the original error with additional context
wrappedErr := fmt.Errorf("encountered an issue: %w", err)
fmt.Println(wrappedErr) // Output: encountered an issue: something went wrong
if err, ok := wrappedErr.(interface{ Unwrap() error }); ok {
// wrappedErr是error類型,只支持Error()方法,所以沒辦法直接調(diào)用Unwrap()。但是wrappedErr.(interface{ Unwrap() error })取出內(nèi)部的數(shù)據(jù)就可以調(diào)用Unwrap()了
fmt.Println("internal error:", err.Unwrap())
}
fmt.Println(errors.Is(wrappedErr, err)) // Output: true
fmt.Println(errors.Is(err, fmt.Errorf("something went wrong"))) // Output: false
}
另外,還有一種interface{ Unwrap() []error },其實(shí)是多次用了%w的結(jié)果。
責(zé)任編輯:武曉燕
來源:
今日頭條