DEV Community

Discussion on: Creating Taboo Error Handler For Go

Collapse
 
kunde21 profile image
Chad Kunde • Edited

This is a common pattern from devs coming from Java/C++/C#/Python/etc. It's not a problem of language design, it's a conflict of expected pattern. The go pattern ends up being fewer lines of code (45 vs 36), even if it handles the error at the top of the call chain instead of the bottom:

package main

import (
  "errors"
  "fmt"
)

func div(a, b int) (int, error) {
  if b == 0 {
    return 0, errors.New("division by zero detected")
  }
  return a / b, nil
}

func callDiv() int {
  result, err = div(10, 0)
  if err != nil {
    return 0, errors.Newf("div error %v", err)
  }
  return result, nil
}

func callCallDiv() (int, error) {
  result, err := callDiv()
  if err != nil {
    return 0, errors.Newf("callCallDiv error %v", err)
  }
  return result, nil
}

func main() {
  c, err := callCallDiv()
  if err != nil {
    fmt.Println(e.Error())
  }
}
Enter fullscreen mode Exit fullscreen mode

The different paradigms from the languages cause us to assume things that aren't necessarily true. Go-style error handling in Java/Python is incredibly verbose, because it's more thorough than the Java/Python pattern. That's neither good nor bad, it's simply a difference of expectations.

Exceptions in Java/Python are considered catastrophic until handled (the infamous "unhandled exception error"), while Go considers them routine until promoted to an exception (panic).

Collapse
 
clavinjune profile image
Clavin June • Edited

yes, I totally agree with you, because it's natural to be verbose for Go. But since using panic could stop the program itself, it is quite dangerous if the user missed 1 wrapper unless you can provide panicHandler.