Golang : Smarter Error Handling with strings.Contains()
Tags : golang error-handling
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
Tags : golang error-handling
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
+2.3k Golang : When to use make or new?
+15.3k Mac OSX : Homebrew and Golang
+2.9k Golang : Write multiple lines or divide string into multiple lines
+2.5k Golang : Progress bar with ∎ character
+2.4k Fix fatal error: evacuation not done in time problem
+2.8k How to tell if a binary(executable) file or web application is built with Golang?
+1.2k Nginx and PageSpeed build from source CentOS example
+2.8k Golang : Convert source code to assembly language
+12.3k Golang : Delete item from slice based on index/key position
+3.7k Golang : Detect user location with HTML5 geo-location
+1.8k Golang : Extract XML attribute data with attr field tag example
+2.2k Golang : Handle sub domain with Gin