Skip to content

Instantly share code, notes, and snippets.

@zelenko
Last active March 6, 2018 22:01
Show Gist options
  • Save zelenko/02eb3b61c44a80deea4029d36987a1f7 to your computer and use it in GitHub Desktop.
Save zelenko/02eb3b61c44a80deea4029d36987a1f7 to your computer and use it in GitHub Desktop.
How to Handle Errors in Go?
# https://gistlog.co/zelenko/02eb3b61c44a80deea4029d36987a1f7
preview: Function can be used to handle errors in GO. Few lines of code can be saved with a function. Instead of three lines of code, one line is sufficient.

Handle errors with the error function

package main

import (
	"fmt"
	"errors"
)

func main() {
	// Go errors:
	result, err := SomeFunction(-4)
	checkErr(err)
	
	fmt.Print("result:", result)
}


func SomeFunction(value int)(n int, err error) {
	if value < 0 {
		return 0, errors.New("Math: negative number passed to Sqrt")
		// another way:
		// return "", fmt.Errorf("Math: negative number passed to Sqrt")
	}
	return value+value, nil
}


func checkErr(err error) {
	if err != nil {
		fmt.Println("Error: ", err.Error())
        	//http.Error(w, "Error: " + err.Error(), 500)
	}
}

Handle error with http:

if err := companiesTemplate.Execute(w, companies); err != nil {
        http.Error(w, "Error: " + err.Error(), 500)
}

Using fmt package

package main

import (
	"fmt"
	"errors"
)

func main() {
	numberList := []int{3,7}
	for i := range numberList {
		word, err := test(numberList[i])
		
		if err != nil {
			fmt.Println("Error: ", err.Error())
		} else {
			fmt.Println("out:", word)
		}
	}
}

func test(number int) (string, error){
	if number < 6 {
		//return "", fmt.Errorf("Number is too small")
		return "", errors.New("number is too small")
	}
	
	return "good", nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment