您当前的位置: 首页 >  golang

少林码僧

暂无认证

  • 2浏览

    0关注

    317博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Go语言(golang)的错误(error)处理的方案

少林码僧 发布时间:2019-01-17 10:17:23 ,浏览量:2

对于Go语言(golang)的错误设计,相信很多人已经体验过了,它是通过返回值的方式,来强迫调用者对错误进行处理,要么你忽略,要么你处理(处理也可以是继续返回给调用者),对于golang这种设计方式,我们会在代码中写大量的if判断,以便做出决定。

func main() {
	conent,err:=ioutil.ReadFile("filepath")
	if err !=nil{
		//错误处理
	}else {
		fmt.Println(string(conent))
	}
}

这类代码,在我们编码中是非常的,大部分情况下error都是nil,也就是没有任何错误,但是非nil的时候,意味着错误就出现了,我们需要对他进行处理。

error 接口

error其实一个接口,内置的,我们看下它的定义

// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
	Error() string
}

它只有一个方法 Error,只要实现了这个方法,就是实现了error。现在我们自己定义一个错误试试。

type fileError struct {
}

func (fe *fileError) Error() string {
	return "文件错误"
}
<
关注
打赏
1661398670
查看更多评论
立即登录/注册

微信扫码登录

0.0356s