简体   繁体   中英

How to match error with dependency injection?

What is the best practice for error matching when using dependency injection?

If we have an interface like this used in a function:

type MyIF interface {
  Send(reciever, msg string) error
}

function mySender(s MyIF) {

  err := s.Send("me@myself.com", "hello")
  if err != nil {
    if err == ??? {
    }
  }
}

How can err be matched? In contrast to an import from a package, I can not import a defined error variable which can be used for comparison or check with.Is().

The solution linked by @Christian works for me (see blog.golang.org/error-handling-and-go ). By adding an Error interface as in the net package in the blog post I can do what I want.

Thanks.

The code snippet would then look like this:

type MyIF interface {
  Send(reciever, msg string) error
}

type MyError interface {
  Error() string
  ReceiverUnknown() bool
}

function mySender(s MyIF) {
  err := s.Send("me@myself.com", "hello")
  if err != nil {
    if nerr, ok := err.(MyError); ok && nerr.ReceiverUnknown() {
      // handle unknown Receiver
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM