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
+5.1k Golang : micron to centimeter example
+8.6k Golang : Convert(cast) []byte to io.Reader type
+11.7k Golang : Display a text file line by line with line number example
+8.9k Golang : Take screen shot of browser with JQuery example
+10k Golang : Translate language with language package example
+17k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+18.8k Golang : convert int to string
+19.7k Golang : Get current URL example
+17.7k Golang : Upload/Receive file progress indicator
+14.1k Golang : Human readable time elapsed format such as 5 days ago
+39.3k Golang : How to read CSV file
+5.5k How to check with curl if my website or the asset is gzipped ?