Error Handling in Go that Every Beginner should Know

Error Handling using Multiple Return Values

func Marshal(v interface{}) ([]byte, error) {
e := &encodeState{}
err := e.marshal(v, encOpts{escapeHTML: true})
if err != nil {
return nil, err
}
return e.Bytes(), nil
}
type error interface {
Error() string
}
// Define your Error struct
type MyError struct {
msg string
}
// Create a function Error() string and associate it to the struct.
func (error *MyError) Error() string {
return error.msg
}
// Now you can construct an error object using MyError struct.
func
ThisFunctionReturnError() error {
return &MyError{"custom error"}
}

Stack Traces

import "errors"func ThisFunctionReturnError() error {
return errors.New("custom error")
}
import (
"github.com/pkg/errors"
"fmt"
)

func A() error {
return errors.New("NullPointerException")
}

func B() error {
return A()
}

func main() {
fmt.Printf("Error: %+v", B())
}
Error: NullPointerException
main.A
/Users/hussachai/Go/src/awesomeProject/error_handling.go:9
main.B
/Users/hussachai/Go/src/awesomeProject/error_handling.go:13
main.main
/Users/hussachai/Go/src/awesomeProject/error_handling.go:17
runtime.main
/usr/local/opt/go/libexec/src/runtime/proc.go:198
runtime.goexit
/usr/local/opt/go/libexec/src/runtime/asm_amd64.s:2361

The Ugly Error Checking

func EatOrange() (*C, error) {
var err error
var a string
a, err = GetA()
if err == nil {
var b string
b, err = GetB(a)
if err == nil {
var c string
c, err = GetC(b)
if err == nil {
return c, nil
}
}
}
return nil, err
}

Opting Out an Error

result, _ := EatOrange() // omit the error assignment
_, err := EatOrange() // omit the result struct

Defer, Panic, and Recover

resp, _ := http.Get("http://golang.org")
defer func () {
if resp != nil {
resp.Body.Close()
}
}()
body, _ := ioutil.ReadAll(resp.Body)
func panic(v interface{}) 
package main

import (
"fmt"
"github.com/pkg/errors"
)

func A() {
defer fmt.Println("A")
defer func() {
if r := recover(); r != nil {
fmt.Printf("Panic: %+v\n", r)
}
}()
B()
}
func B() {
defer fmt.Println("B")
C()
}
func C() {
defer fmt.Println("C")
Break()
}
func Break() {
defer fmt.Println("D")
panic(errors.New("the show must go on"))
}
func main() {
A()
}

Converting Panicking into a Returned Error.

func Perform() (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
GoesWrong()
return
}
func GoesWrong() {
panic(errors.New("Fail"))
}
func main() {
err := Perform()
fmt.Println(err)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store