41
Prepare Yourself To Deal With Golang Error Handling
Golang has an unconventional approach and that’s the reason why people like to talk about Golang. Golang has its way of Go Error handling, while other languages handle the error by try... catch block. As Golang has its unique way of handling errors, it is challenging for developers to get all information about Go’s Error handling method. So, In this article, we will discuss Golang Error Handling Best Practices. The article will help developers to understand Golang Error Handling in a better way. Plus, we are also going to have a look at why Golang has a better approach than other programming languages.
So, let’s have a look at it First.
What are Error and Error Handling?
It’s unfair; if without understanding Error and Error handling, I move to Golang Error Handling’s technique.
Error: Those unusual and unwanted conditions that occur in the program are known as errors. The error can exist at the time of compile or run time. Some examples of errors are - failed db connection, invalid user inputs, or file does not exist.
Now, if your program behaves abnormally, you try to implement the solution and predict where things go wrong - it’s known as Error Handling. Many languages like Java, Python, or PHP use try...catch block for Error Handling.
Now, let’s understand what Golang’s way of handling errors is.
Golang Error Handling Patterns
Dealing with new technology or language has always been difficult; it doesn’t matter how easy and straightforward it is. And, when you get frustrated while learning about new things, you start criticizing. That’s exactly what Go has to face. It’s challenging for developers to understand Go’s way of error handling. Go error handling has so much to learn about, but first, let’s look at the built-in error type of Golang.
Error type
In Go’s, the type of interface is known as error type. It declares itself as a string.
Its looks like this-
type error interface {
Error() string
}
Error() string
}
Error Handling Patterns in Go
Golang doesn’t overlook the errors, and they take them very important. If you just start learning about Go, The syntax of func f() (value, error) is very easy to understand and smooth to implement.
Golang uses errors as first-class values of the functions. If you missed returning the error string from your function like this way -
func getUsers() (*Users, error) { .... }
func main() {
users, _ := getUsers()
}
users, _ := getUsers()
}
Let’s have one example of Error handling practice in Go.
if error := criticalOperation(); error != nil {
// Not returning anything is a bad practice.
log.Printf("Oops! Something went wrong in the program", error)
//
}
// Not returning anything is a bad practice.
log.Printf("Oops! Something went wrong in the program", error)
//
return
your error message hereafter this line!}
if error := saveData(data); error != nil {
return fmt.Errorf("Data has been lost", error)
}
return fmt.Errorf("Data has been lost", error)
}
If err != nil is encountered while calling criticalOperation() and you choose to log the error message instead of handling it intelligently, at that time, Go won’t save your program from the errors. Golang just guides you on how to return and use the errors; further. It’s upto you how you handle errors.
Golang uses the panic and recover method rather than throwing exceptions and using try…catch block. We will be going to discuss that later on. Hope upto here you will get a basic understanding of Go error handling. Now let’s understand why Go is best, and for the same, we need to know how different languages handle their errors.
Throwing exception: Error handling way of other programming languages
Developers working on Java, Python, PHP, Javascript frameworks, and PHP are well aware of how these languages handle errors.
Code snippet of how to throw an exception:-
try {
criticalDataOperation1();
criticalDataOperation2();
criticalDataOperation3();
} catch (err) {
console.error(err);
}
criticalDataOperation1();
criticalDataOperation2();
criticalDataOperation3();
} catch (err) {
console.error(err);
}
This is not the only way of error handling; Rust is also in the race. Rust has a good pattern with simple coding to find errors and get similar results like exceptions.
Now the ques is why Golang didn’t utilize exceptions, a conventional way of error handling, and came up with such a unique approach? Let’s have a look.
Why didn’t Golang utilize exceptions, a conventional way to handle errors?
Keep these two hey points in mind while Golang error handling is:
➼ Keep it simple.
➼ Plan where it can go wrong.
➼ Plan where it can go wrong.
Here are the advantages of Golang new error handling.
No interruption of sudden uncaught exceptions.
Simple syntax.
You have complete control over the errors
Transparent control-flow.
Easy implementation of error chains to take action on the error.
Simple syntax.
You have complete control over the errors
Transparent control-flow.
Easy implementation of error chains to take action on the error.
It looks like the last point is confusing you. Right? Let make it more clear. Until you have reached the actual error, if err != nil allows you to chain the functions returning errors throughout your program’s hierarchy. It’s relatively easy to debug for the developer’s team.
Example for error-chaining.
// controllers/users.go
if error := db.CreateUserforDB(user); error != nil {
return fmt.Errorf("error while creating user: %w", error)
}
if error := db.CreateUserforDB(user); error != nil {
return fmt.Errorf("error while creating user: %w", error)
}
// database/users.go
func (db *Database) CreateUserforDB(user *User) error {
ok, error := db.DoesUserExistinDB(user)
if error != nil {
return fmt.Errorf("error in db while checking: %w", err)
}
...
}
func (db *Database) CreateUserforDB(user *User) error {
ok, error := db.DoesUserExistinDB(user)
if error != nil {
return fmt.Errorf("error in db while checking: %w", err)
}
...
}
func (db *Database) DoesUserExistinDB(user *User) error {
if error := db.Connected(); error != nil {
return fmt.Errorf("error while establishing connection: %w", err)
}
...
}
if error := db.Connected(); error != nil {
return fmt.Errorf("error while establishing connection: %w", err)
}
...
}
func (db *Database) Connected() error {
if !isInternetConnectionEstablished() {
return errors.New("not connected to internet")
}
...
}
if !isInternetConnectionEstablished() {
return errors.New("not connected to internet")
}
...
}
Upto here, we have learned Golang Error Handling best practices and fundamental way of using if…err != nil. Now, let’s understand Golang Error Handling: Panic and Recover Mechanism.
Golang Error Handling: Panic and Recover Mechanism
Golang has panic and recover, unlike other languages. You might be well aware of the try...catch block. But the exception handling is not so exceptionally handled. Sometimes for the custom error messages, developers use exception handling. You need to avoid such practices. On the other hand, Golang has a different way for the custom error.
The panic and recover technique is used in exceptional cases only.
Panicking
exceptionalCondition := true
if exceptionalCondition {
panic("panicking!!")
}
if exceptionalCondition {
panic("panicking!!")
}
It’s more manageable to create panic in programs than handling it.
Recover: to rescue from panic.
func F() {
defer func() {
if error := recover(); error != nil {
fmt.Println("This is the error: ", err)
}()
//do whatever here...
}
defer func() {
if error := recover(); error != nil {
fmt.Println("This is the error: ", err)
}()
//do whatever here...
}
It is a quality overlook of what is panic and recover mechanism and how does it work.
Conclusion
So, here we have ended up discussing the basics of Golang Error Handling. We covered How Go is better than other languages, and we also looked at the overview of panic and recovery mechanisms. I believe that you get the help that you are expecting from this article. If you want to implement the Golang Error handling: Best Practices for your organization, contact the best Golang web development company. That helps you to turn your unique idea into a reality by taking care of your business needs.