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.8k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+25.8k PHP : Count number of JSON items/objects
+2.1k Golang : Switch Redis database redis.NewClient
+13.3k Golang : Normalize unicode strings for comparison purpose
+19.1k Golang : Saving private and public key to files
+13.4k Golang : Execute function at intervals or after some delay
+12.3k Golang : Check if an integer is negative or positive
+15.9k Golang : How to save log messages to file?
+12k Golang : Convert(cast) int to int64
+8.7k Golang : Detect number of faces or vehicles in a photo
+18.1k Golang : Check if os.Stdin input data is piped or from terminal
+15.3k CodeIgniter/PHP : Create directory if does not exist example