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
+4.6k Mac OSX : Get disk partitions' size, type and name
+6k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+13.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+6.6k Golang : Experimental emojis or emoticons icons programming language
+11.4k Golang : Concatenate (combine) buffer data example
+5.3k Golang : How to deal with configuration data?
+19.6k Golang : Archive directory with tar and gzip
+21.8k Golang : Use TLS version 1.2 and enforce server security configuration over client
+29.5k Golang : Record voice(audio) from microphone to .WAV file
+7.4k Golang : Shuffle strings array
+11.3k Golang : Post data with url.Values{}
+12.2k Golang : Get month name from date example