Go rauljordan.com

This is why Go’s error handling is awesome  ↦

// In controllers/user.go
if err := database.CreateUser(); err != nil {
    log.Errorf("Could not create user: %v", err)
}

// In database/user.go
func CreateUser() error {
    if err := db.SQLQuery(userExistsQuery); err != nil {
        return fmt.Errorf("could not check if user already exists in db: %v", err)
    }
    ...
}

// In database/sql.go
func SQLQuery() error {
    if err := sql.Connected(); err != nil {
        return fmt.Errorf("could not establish db connection: %v", err)
    }
    ...
}

// in sql/sql.go
func Connected() error {
    if noInternet {
        return errors.New("no internet connection")
    }
    ...
}

The beauty of the code above is that each of these errors are completely namespaced by their respective function, are informative, and only handle responsibility for what they are aware of. This sort of error chaining using fmt.Errorf("something went wrong: %v", err) makes it trivial to build awesome error messages that can tell you exactly what went wrong based on how you defined it.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00