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 –
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,
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:
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 } }
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) } }
The FatalIn will show complete error along with date and time
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.
Panic is good if you want to see some of the stack.
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) }
“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 }
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”
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork