4 回答

TA貢獻1844條經(jīng)驗 獲得超8個贊
我第一次嘗試解決方案:
package main
import (
"errors"
"fmt"
)
var noMoreBeer = errors.New("no more beer")
func thisFails() error {
// returns my specific error, but could also percolate some other errors up
return noMoreBeer
}
func main() {
err := thisFails()
if err != nil {
if err == noMoreBeer {
fmt.Println("go buy some beer")
} else {
panic("something unexpected happened")
}
}
}
我理解閱讀 https://blog.golang.org/go1.13-errors 的關鍵點是,我可以針對類型為 .這在功能上等同于我開始使用的Python示例。error

TA貢獻1858條經(jīng)驗 獲得超8個贊
我們一直在生產(chǎn)中使用錯誤,通過cutome實現(xiàn)錯誤接口,沒有任何問題。這有助于檢測錯誤并更有效地找到根本原因。
package errors
type Error struct {
err error // the wrapped error
errType ErrorType
errInfo ErrorInfo
op Op
// domain specific data
userID int
requestID string
}
type (
ErrorType string
ErrorInfo string
Op string
)
var NoMoreBeer ErrorType = "NoMoreBeerError"
func (e Error) Error() string {
return string(e.errInfo)
}
func Encode(op Op, args ...interface{}) error {
e := Error{}
for _, arg := range args {
switch arg := arg.(type) {
case error:
e.err = arg
case ErrorInfo:
e.errInfo = arg
case ErrorType:
e.errType = arg
case Op:
e.op = arg
case int:
e.userID = arg
case string:
e.requestID = arg
}
}
return e
}
func (e Error) GetErrorType() ErrorType {
return e.errType
}
通過這種方式,您可以使用錯誤,但可以根據(jù)需要添加擴展功能。
e := errors.Encode(
"pkg.beerservice.GetBeer",
errors.NoMoreBeer,
errors.ErrorInfo("No more beer available"),
).(errors.Error)
switch e.GetErrorType() {
case errors.NoMoreBeer:
fmt.Println("no more beer error")
fmt.Println(e.Error()) // this will return "No more beer available"
}
操場上的工作示例:https://play.golang.org/p/o9QnDOzTwpc

TA貢獻1799條經(jīng)驗 獲得超6個贊
您可以使用類型開關。
package main
import "fmt"
// the interface
type NoMoreBeerError interface {
noMoreBeer() bool
}
// two different implementations of the above interface
type noMoreBeerFoo struct { /* ... */ }
type noMoreBeerBar struct { /* ... */ }
func (noMoreBeerFoo) noMoreBeer() bool { return true }
func (noMoreBeerBar) noMoreBeer() bool { return false }
// have the types also implement the standard error interface
func (noMoreBeerFoo) Error() string { return " the foo's error message " }
func (noMoreBeerBar) Error() string { return " the bar's error message " }
func thisFails() error {
if true {
return noMoreBeerFoo{}
} else if false {
return noMoreBeerFoo{}
}
return fmt.Errorf("some other error")
}
func main() {
switch err := thisFails().(type) {
case nil: // all good
case NoMoreBeerError: // my custom error type
if err.noMoreBeer() { // you can invoke the method in this case block
// ...
}
// if you need to you can inspect farther for the concrete types
switch err.(type) {
case noMoreBeerFoo:
// ...
case noMoreBeerBar:
// ...
}
default:
// handle other error type
}
}
- 4 回答
- 0 關注
- 113 瀏覽
添加回答
舉報