4 回答

TA贡献1844条经验 获得超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条经验 获得超8个赞
我们一直在生产中使用错误,通过cutome实现错误接口,没有任何问题。这有助于检测错误并更有效地找到根本原因。
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
}
通过这种方式,您可以使用错误,但可以根据需要添加扩展功能。
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条经验 获得超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 关注
- 134 浏览
添加回答
举报