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
+3.7k MariaDB/MySQL : How to get version information
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+13.7k Golang : Get all local users and print out their home directory, description and group id
+4.6k PHP : Convert CSV to JSON with YQL example
+11.4k Golang : "https://" not allowed in import path
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+13.9k Golang : How to get Unix file descriptor for console and file
+10.7k Golang : Perform sanity checks on filename example
+6.4k Golang : Example of how to detect which type of script a word belongs to
+7.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+6.6k Gogland : Single File versus Go Application Run Configurations
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode