Golang Error Handling

In Chapter-6 of our Golang Tutorial, we touched upon ‘Concurrency’ in Golang. 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 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

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks