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
+14.7k Golang : How to pass map to html template and access the map's elements
+8.1k Golang : Gomobile init produce "iphoneos" cannot be located error
+7.6k Golang : Check to see if *File is a file or directory
+14.8k Golang : Convert(cast) int to float example
+15.1k Golang : Basic authentication with .htpasswd file
+32k Golang : How to convert(cast) string to IP address?
+10.8k Golang : How to delete element(data) from map ?
+29.4k Golang : missing Git command
+6.3k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+36.3k Golang : Get file last modified date and time
+12.6k Golang : Encrypt and decrypt data with x509 crypto
+9.2k Golang : Capture text return from exec function example