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
+28.1k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+5.3k Golang : Customize scanner.Scanner to treat dash as part of identifier
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+5.7k Python : Print unicode escape characters and string
+10.8k Android Studio : Simple input textbox and intercept key example
+9.4k Golang : How to control fmt or log print format?
+8.4k Golang: Prevent over writing file with md5 hash
+12.4k Golang : Display list of countries and ISO codes
+5.5k Golang : PGX CopyFrom to insert rows into Postgres database
+12.8k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+7.7k Golang : How to stop user from directly running an executable file?