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

戚弘和
2023-12-01

对于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 "文件错误"
}
<
 类似资料: