Golang : Smarter Error Handling with strings.Contains()
In this tutorial, we will learn some simple trick with strings.Contain() function on capturing the error message and handling it according to the error message.
Most of the Go source code will typically use these lines of codes to handle error.
For example :
if err != nil {
panic(err)
}
or
if err!= nil {
fmt.Println(err.Error())
os.Exit(1)
}
Let's see how error can be handled in a smarter way. This block of code will first evaluates the error string and then do the necessary action.
if !strings.Contains(err.Error(), "timed out") {
fmt.Printf("resulting error not a timeout: %s", err)
}
or
if strings.Contains(err.Error(), "overflow") {
// DO SOMETHING TO RECOVER THE OVERFLOW
}
Hope you will find this short Golang tutorial useful
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.8k Golang : Build and compile multiple source files
+11k Golang : Encrypt and decrypt data with x509 crypto
+6.3k Golang : Dealing with postal or zip code example
+6.1k Golang : Array mapping with Interface
+13.2k Golang : On enumeration
+25.3k Golang : Force your program to run with root permissions
+7.9k Golang : automatically figure out array length(size) with three dots
+16.1k Golang : When to use init() function?
+7.3k Golang : How to check variable or object type during runtime?
+14.9k Golang : convert string or integer to big.Int type
+16.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography