Multiple Error Handling

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 determine what type of error occurred (internal, results not found in db, etc.) and then process accordingly in function 1?

+4
source share
1 answer

You have 3 main options:

  • based on the line, that is, to view the message. This, of course, is not bad, because if you later change one letter in the message, you need to rewrite the entire verification code so that I avoid it.

  • If the error messages can remain constant, simply create the errors as global variables, and then compare the received error with the known predetermined one.

For instance:

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. , - , .

:

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}
}

, , - :

// 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
}

:

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
       ....
     }  
   }
}
+5

Source: https://habr.com/ru/post/1589266/


All Articles