Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error handling in Go

I've been reading this blog post but I'm still not convinced I know exactly what to do to get custom errors that I can return from my functions and handle outside of them.

This is what I'm currently doing:

func doSomething() int {
    x := 0
    // Do something with x.
    ...
    if somethingBadHappened {
        return -1
    }
    if somethingElseBadHappened {
        return -2
    }
    return x
}

This is what I'd like to be doing:

func doSomething() int, ? {
    ...
    if somethingBadHappened {
        return ?, err
    }
    if somethingElseBadHappened {
        return ?, err2
    }
    return x, nil
}

But I'm not exactly sure how, and what to replace those question marks with.

like image 811
Tom Carrick Avatar asked Dec 15 '22 13:12

Tom Carrick


1 Answers

You don't really need to return an int if you don't want to. You can do something like:

func doSomething() error {
  ...
  if somethingBadHappened {
      return errors.New("something bad happened")
  }
  if somethingElseBadHappened {
      return errors.New("something else bad happened")
  }
  return nil
}

or if you want to return ints

func doSomething() (int, error) {
  ...
  if somethingBadHappened {
      return -1, errors.New("something bad happened")
  }
  if somethingElseBadHappened {
      return -2, errors.New("something else bad happened")
  }
  return x, nil
}

be sure to import "errors" at the top.

If you want to test whether you got an error, you can do

x, err := doSomething()
if err != nil {
  log.Println(err)
}
like image 100
kdar Avatar answered Jan 11 '23 18:01

kdar