douhan1860 2015-05-21 18:06
浏览 34
已采纳

处理多个错误

I have Function 1:

func Function1() {
    if err := Function2(); err != nil {

    }
}

and Function2:

func Function2() error {
    if err := doSomethingThatMightCauseError(); err != nil {
        return errors.New("Error Type 1")
    }

    if err := doSomethingElseThatMightCauseError(); err != nil {
        return errors.New("Error Type 2")
    }
}

How can I detect what type of error has happened (internal, no results found in db etc) and then handle accordingly in Function 1?

  • 写回答

1条回答 默认 最新

  • dousong2967 2015-05-21 18:12
    关注

    You have 3 main options:

    1. string based, i.e. looking into the message. This is of course pretty bad because if you later change one letter in the message, you need to rewrite all the checking code, so I'd avoid it.

    2. If the error messages can stay constant, simply create errors as global variables, and then compare the received error with a known pre-defined one.

    For example:

    var ErrDB = errors.New("Database Error")
    var ErrTimeout = errors.New("Timeout") //or whatever
    

    and then

    if err := someFunc(); err != nil {
      switch err {
      case ErrDB:
        //do stuff that needs to be done here
      case ErrTimeout:
        //etc /etc
      }
    }
    
    1. Create a custom error type, since errors are just interfaces, that can have some identifier or other contextual data.

    For example:

    const (
      ErrDB = 1
      ErrTimeout = 2
      ...
    )
    
    type MyError struct {
       Code int
       Message string
    }
    
    // This is what you need to be an error
    func (e MyError)Error() string {
       return e.Message
    }
    
    
    func NewError(s string, code int) error {
       return MyError{s,code}
    }
    

    and then when you return it do something like this:

    // Return a MyError with a DB code for db operations
    func someFunc() error {
       if err := talkToDB(); err != nil {
          return NewError(err.Error(), ErrDB)
       }
       return nil
    }
    

    and when analyzing it:

    if err := someFunc(); err != nil {
    
       // check if this is a MyError
       if me, ok := err.(MyError); ok {
         // now we can check the code
         switch me.Code {
           case ErrDB:
             //handle this
           ....
         }  
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改