本文摘自php中文网,作者V,侵删。

正确处理方法:
一、失败的原因只有一个时,不使用error
例如:
1 2 3 4 5 6 7 8 9 | 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)
}
|
我们可以看出,该函数失败的原因只有一个,所以返回值的类型应该为bool,而不是error,重构一下代码:
1 2 | func (self *AgentContext) IsValidHostType(hostType string) bool {
return hostType == "virtual_machine" || hostType == "bare_metal" }
|
说明:大多数情况,导致失败的原因不止一种,尤其是对I/O操作而言,用户需要了解更多的错误信息,这时的返回值类型不再是简单的bool,而是error。
二、没有失败时,不使用error
error在Golang中是如此的流行,以至于很多人设计函数时不管三七二十一都使用error,即使没有一个失败原因。
我们看一下示例代码:
1 2 3 | func (self *CniParam) setTenantId() error {
self.TenantId = self.PodNs
return nil}
|
对于上面的函数设计,就会有下面的调用代码:
阅读剩余部分
相关阅读 >>
【go】go语言资料包
微服务实战go micro v3 系列(二)- helloworld
protoc go插件编写之四 (实现生成自己的proto文件)
golang 获取win进程信息(pid,进程名称等信息)
golang实现插入排序
解决golang中vendor引起的相同类型,却提示类型不一样问题
分享一些为phper准备的go入门知识
golang可以写web吗?
protoc 插件编写之一 (protoc 插件的原理)
golang语言学习之go语言变量
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » golang返回错误时如何正确处理