Correct handling method:
1. When there is only one reason for failure, do not use error
For example:
func (self *AgentContext) CheckHostType(host_type string) error { switch host_type { case "virtual_machine": return nil case "bare_metal": return nil } return errors.New("CheckHostType ERROR:" + host_type) }
We can see that there is only one reason for the failure of this function, so the type of the return value should be bool, not error. Refactor the code:
func (self *AgentContext) IsValidHostType(hostType string) bool { return hostType == "virtual_machine" || hostType == "bare_metal"}
Explanation: In most cases, resulting in There is more than one reason for failure, especially for I/O operations, users need to know more error information. At this time, the return value type is no longer a simple bool, but error.
2. Don’t use error when there is no failure
error is so popular in Golang that many people don’t care about anything when designing functions. Use error even if there is no failure reason.
Let’s take a look at the sample code:
func (self *CniParam) setTenantId() error { self.TenantId = self.PodNs return nil}
For the above function design, there will be the following calling code:
err := self.setTenantId() if err != nil { // log // free resource return errors.New(...) }
Refactor the code based on our correct posture :
func (self *CniParam) setTenantId() { self.TenantId = self.PodNs }
Then the calling code becomes:
self.setTenantId()
3. Error should be placed at the end of the return value type list
For the return value type error , used to pass error information, usually placed last in Golang.
resp, err := http.Get(url) if err != nil { return nill, err }
The same goes for bool as the return value type.
value, ok := cache.Lookup(key) if !ok { // ...cache[key] does not exist… }
4. When errors are passed layer by layer, logs are added at each layer
Adding logs at each layer is very convenient for fault location.
Recommended related articles and tutorials: golang tutorial
The above is the detailed content of How to handle correctly when golang returns an error. For more information, please follow other related articles on the PHP Chinese website!