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
+20.2k SSL : How to check if current certificate is sha1 or sha2
+10.1k CodeIgniter : How to check if a session exist in PHP?
+7.9k Golang : Take screen shot of browser with JQuery example
+13.7k nginx: [emerg] unknown directive "ssl"
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+13.7k Golang : Get all local users and print out their home directory, description and group id
+12.3k Golang : Get constant name from value
+22.8k Golang : Daemonizing a simple web server process example
+18.3k Golang : Count JSON objects and convert to slice/array
+6.3k Golang : Calculate how many weeks left to go in a given year
+12.3k Golang : Set image canvas or background to transparent
+5.6k Elasticsearch : Shutdown a local node