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
+12.7k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+21.3k Golang : Create and resolve(read) symbolic links
+7.9k Golang : Getting Echo framework StartAutoTLS to work
+5.3k Javascript : Change page title to get viewer attention
+12.4k Golang : How to check if a string starts or ends with certain characters or words?
+9.8k Golang : List available AWS regions
+8.3k Prevent Write failed: Broken pipe problem during ssh session with screen command
+9.8k Random number generation with crypto/rand in Go
+8.2k Golang : Routes multiplexer routing example with regular expression control
+5.9k Golang : Use NLP to get sentences for each paragraph example
+8.2k How to show different content from website server when AdBlock is detected?
+9.7k PHP : Get coordinates latitude/longitude from string