RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 13: Errors in Go – Failing Gracefully Like a Grown-Up ❌✅

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

In Go, errors are not scary red screens.
They’re just values you check after doing something.

Imagine this:

milk, err := BuyMilk()

If err is nil, you’re good.
If err has a value, something went wrong.

The Go built-in error type is an interface:

type error interface {
  Error() string
}

That means anything that implements this can be used as an error.

package main
import (
  "errors"
  "fmt"
)
func divide(a, b int) (int, error) {
  if b == 0 {
    return 0, errors.New("you can’t divide by zero!")
  }
  return a / b, nil
}
func main() {
  result, err := divide(10, 0)
  if err != nil {
    fmt.Println("Oops:", err)
  } else {
    fmt.Println("Result:", result)
  }
}

🧠 If you try to divide by 0, the function doesn’t crash.
It just gives you an error — and you decide what to do.

Go’s philosophy is:

Be explicit. Always check for errors.

It might feel repetitive at first…

data, err := doSomething()
if err != nil {
  return err
}

But it’s clear.
No hidden exceptions.
No guessing.

You can even make your own:

type MyError struct {
  Message string
}
func (e MyError) Error() string {
  return "Error happened: " + e.Message
}

Now return it like this:

return MyError{Message: "something broke"}

Calling a function in Go is like asking a friend:

“Hey, did that thing work?”

And they always answer:

  • “Yup, here’s your result!”

  • or “Nope, something broke, here's why.”

No drama. Just chill.

  • Errors in Go are values, not exceptions

  • Always check if err != nil

  • Use errors.New() or make your own error types

  • No try/catch — just clean, readable code

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.