DEV Community

Shift / Reinhart Previano K.
Shift / Reinhart Previano K.

Posted on • Originally published at reinhart1010.id

DRY-ing Go/Golang’s error handling with underscores.

The Go Programming Language, also preferred by others as Golang, doesn’t include the concept of Exceptions and try-catch like Java. This is why many functions and libraries built around it are meant to be written like this:

output, err := somelib.SomeCoolFunction()
Enter fullscreen mode Exit fullscreen mode

If you are writing simple programs with Go, there are many cases that you just don’t put much care on error-handling. If you, for example, just want the program to exit and informing the error message, you might most likely to do this:

data1, err := somelib.SomeCoolFunction()
if err != nil {
  log.Fatal(err)
}

data2, err := anotherlib.AnotherCoolFunction()
if err != nil {
  log.Fatal(err)
}

err := somelib.SaveTheseCoolData(data1, data2)
if err != nil {
  log.Fatal(err)
}
Enter fullscreen mode Exit fullscreen mode

Well, that’s bad if you try to place the exact same if conditions for every methods, just because you don’t want to take much care in handling errors. This is why I decided to simplify things by introducing two new functions, __(err) and ___(res, err)!

func __(err error) {
  if err != nil {
    log.Fatal(err)
  }
}

func ___[T interface{}](res T, err error) T {
  if err != nil {
    log.Fatal(err)
  }
  return res
}
Enter fullscreen mode Exit fullscreen mode

Completely good for “Don’t Repeat Yourself” (DRY). But remember, if you have more than one package, you will need to repeat writing the same functions to get the same convenience for every different package, because these underscore names are not considered as public functions.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay