Golang Error Handling

In Chapter-6 of our Golang Tutorial, we touched upon ‘Concurrency’ in Golang new project. In this chapter, let’s explore ‘Error Handling’.

Whenever you come across any runtime problem while executing your Go application that is an error. Go doesn’t have an exception but in Go, it is in form of panic and recover. Go has a simple and easy way of handling when something goes wrong in program. Basically, Go is having the ability to return multiple values.

By convention, if something goes wrong then the function returns an error as its last return value.

func sayHello(msg string) (string,error){
//your code goes here
}

An error type is an interface which is there in errors package of Golang.

type error interface{
Error( ) string
}

This means any type that implements Error( ) returns a string satisfying error interface. The string returned gives message so that we can find what went wrong.

response,err:=sayHello(“George”)
If err!=nil {
// handle error
}
//do something

Here err!=nil means err value is having some values. So, if err contains some values that means error occurred there and we need to handle this.

In Go, error handling is very important. As in above example, we have to check error every time.

In Go, function passes error just like types and as per Robert Pike’s blog errors are valued https://blog.golang.org/errors-are-values

An error in Go must either be –

  • handled/ignored right there, or
  • returned to caller

For example, os.Open() returns non-nil value when fails to open file.

func Open(name string)(file *File,err error)

Find the below example –

main.go
package main
import (
"fmt"
"os"
)
func main() {
_, err := os.Open("fileOne.txt")
if err != nil {
fmt.Println("Error Happened", err)
}
}

Here, above if os.Open( ) fails to open a file then it will return err with the message like,

Golang Error Handling

Here in the below example of web service, if some unexpected server-side error were to happen, we would generate 5xx error. So you have to do like this –

func init() {
http.HandleFunc("/users", viewUsers)
http.HandleFunc("/companies", viewCompanies)
}

func viewUsers(w http.ResponseWriter, r *http.Request) {
// some code
if err := userTemplate.Execute(w, user); err != nil {
http.Error(w, err.Error(), 500)
}
}

func viewCompanies(w http.ResponseWriter, r *http.Request) {
// some code
if err := companiesTemplate.Execute(w, companies); err != nil {
http.Error(w, err.Error(), 500)
}
}

Here we have to repeat the same error handling code across all of our handler functions.

The most commonly used error’s implementation is the error package’s unexported type errorString.

// errorString is a trivial implementation of error.
type errorString struct {
s string
}

func (e *errorString) Error() string {
return e.s
}

You can construct one of these values with the errors. New function. It takes a string that it converts to an errors.errorString and returns as an error value.

// New returns an error that formats as the given text.
func New(text string) error {
return &errorString{text}
}

Here’s how you might use errors. New:

func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("math: square root of negative number")
}
// implementation
}

A caller passing a negative argument to Sqrt receives a non-nil error value (whose concrete representation is an errors.errorString value). The caller can access the error string (“math: square root of…“) by calling the error’s Error method, or by just printing it:

 

Are You Looking For Golang Development Services?

Errors Logging To File

The Golang has given a standard library package “log” for implementing logging and that will write the standard error and also the date and time of each logged message.

main.go
package main
import (
"fmt"
"log"
"os"
)

func init() {
nsf, err := os.Create("log.txt")
if err != nil {
fmt.Println(err)
}
log.SetOutput(nsf) /* sets the output to file via pointer */
}
func main() {
_, err := os.Open("a.txt")
if err != nil {
log.Println("Error present there", err) //write to log file
fmt.Print(err) //write to console
}
}

Golang Error HandlingGolang Error Handling

Here the log.txt file is created with error information.

log.Println() calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println.

Fatalln is also same as Println followed by a call to os.Exit()

main.go
package main
import (
"fmt"
"log"
"os"
)
func main() {
_, err := os.Open("fileOne.txt")
if err != nil {
fmt.Println("Error Happened", err)
log.Fatalln("Error Happened", err)
}
}

Golang Error Handling Golang Error Handling

The FatalIn will show complete error along with date and time

Panic

A panic means something went wrong unexpectedly. Mostly we use it to fail fast on errors that shouldn’t occur during normal operations.
We’ll use panic to check for unexpected errors. A panic is used to abort if function returns an error value that we don’t know how to handle.

func main() {
elements := []int{3, 5, 2, 6, 2}
arrays := make([ ]int, 0, 3) //Creating slice with make( )
for n := range elements {
fmt.Println("Elements", n)
}
for i := 0; i < 80; i++ {
arrays = append(arrays, i) // to append i elements to slice
fmt.Println("Len:", len(arrays), "Capacity:", cap(arrays),
"Value: ", arrays[i])
}}

After running this program, if we get an error, it will cause it to panic and returns error message and goroutine traces and exits with nonzero status.Golang Error Handling

Panic is good if you want to see some of the stack.

Recover

Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.

main.go
package main
import "fmt"

func main() {
f()
fmt.Println("Returned normally from f.")
}

func f() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
}

func g(i int) {
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
}
defer fmt.Println("Defer in g", i)
fmt.Println("Printing in g", i)
g(i + 1)
}

Golang Error Handling

Custom Errors

“Error values in Go aren’t special, they are just values like any other,so you have entire language at your disposal”.
So we can create custom errors for user understanding.

In the “errors” package Go has provided a func New(text string)error for manipulating errors.

main.go
package main
import (
"errors"
"log"
)
func main() {
_, err := Sqrt(-10)
if err != nil {
log.Fatalln(err)
}
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("norgate math: square root of negative number") /* for user defined error message */
}
return f * f, nil
}

Golang Error Handling

A struct is defined by using type and struct keyword along with the meaningful name

As we have seen ‘Error Handling’ in this chapter, let’s move to the next one and see “Common Utilities in Golang Project”

Content Team

This blog is from Mindbowser‘s content team – a group of individuals coming together to create pieces that you may like. If you have feedback, please drop us a message on contact@mindbowser.com

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?