A LITTLE CORNER OF MY WORLD

Read a few words, keep a little time

Every moment worth recording has a light of its own.

Back to all posts
Learn code

Error handling in Go

When writing a Go program, you end up writing a lots of err != nil, you can avoid this.

On this page
  1. Gracefully message
  2. Multiple Errors
  3. Avoid err := nil repetition
  4. Is
  5. Your own messages error
  6. Another avoid repetition

In Go, when all is fines, error return nil

Gracefully message

func testFunction(a int) (int, error) {
  if a < 15 {
    return a, fmt.Errorf("test function will return error", a)
    // Or even: return a, errors.New("test function will return error")
  }
  return a, nil
}

func main() {
  val, err := testFunction(10)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
}

Multiple Errors

func ValidatePerson(p Person) {
  var errs []error
  if len(p.FirstName) == 0 {
    errs = append(errs, errors.New("field FirstName cannot be empty"))
  }
  if len(p.LastName) == 0 {
    errs = append(errs, errors.New("field LastName cannot be empty"))
  }
  if len(errs) > 0 {
    return errors.Join(errs...)
  }
  return nil
}

Avoid err := nil repetition

type safeWritter struct {
  w io.Writer
  Error error
}

func (sw *safeWritter) Write(data []byte) {
  if sw.Error != nil {
    return
  }
  _, err := sw.w.Write(data)
  if err != nil {
    sw.Error = err
  }
}

func write(w io.Writer) error {
  metadata := []byte("Hello\n")
  sw := safeWritter{w: w}
  sw.Write(metadata)
  return sw.Error
}

Is

Is allow you to search the type of Sentinel error. if errors.Is(err, fs.ErrExist) is preferable to if err == fs.ErrExist

func fileChecker(name string) error {
  f, err := os.Open(name)
  if err != nil {
    return fmt.Errorf("in fileChecker: %w", err)
  }
  f.Close()
  return nil
}

func main() {
  err := fileChecker("not_here.txt")
  if err != nil {
    if errors.Is(err, os.ErrNotExist) {
      fmt.Println("That file doesn't exist")
    }
  }
}

Your own messages error

type Status int
// enumeration
const (
  InvalidLogin Status = iota + 1
  NotFound
)
// custom struct
type StatusErr struct {
  Status Status
  Message string
}
func (se StatusErr) Error() string {
  return se.Message
}

// Usage example, always return a type error
func LoginAndGetData(uid, pwd, file string) ([]byte, error) {
  token, err := login(uid, pwd)
  if err != nil {
    return nil, StatusErr{
      Status: InvalidLogin,
      Message: fmt.Sprintf("Invalid credential for user %s", uid)
    }
  }
  data, err := getData(token, file)
  if err != nil {
    return nil, StatusErr{
      Status: NotFound,
      Message: fmt.Sprintf("file not found", file)
    }
  }
  return data, nil
}

Another avoid repetition

// The main function, public, one error check
func ProcessOrder(orderID int) error {
    if err := validateAndCharge(orderID); err != nil {
        return fmt.Errorf("processing order %d: %w", orderID, err)
    }
    return fulfillOrder(orderID)
}

// A private for validate
func validateAndCharge(orderID int) error {
    order, err := db.GetOrder(orderID)
    if err != nil { return err }

    user, err := db.GetUser(order.UserID)
    if err != nil { return err }

    return chargeCard(user.CardID, order.Total)
}
✿

Thank you for reading. I hope these words were useful.

Szorfein
Szorfein / Author

A little code, a little everyday life. Say hello in the guestbook. Guestbook