首页 文章资讯内容详情

Golang中的error类型

2026-06-01 4 花语

本文内容纲要:

####Golang中的error类型error类型本身就是一个预定义好的接口,里面定义了一个method

typeerrorinterface{ Error()string } 生成一个新的error并返回

一般有以下几种处理方式:

packagemain import( "errors" "fmt" ) typeCustomerrorstruct{ infoastring infobstring Errerror } func(cerrCustomerror)Error()string{ errorinfo:=fmt.Sprintf("infoa:%s,infob:%s,originalerrinfo:%s",cerr.infoa,cerr.infob,cerr.Err.Error()) returnerrorinfo } funcmain(){ //方法一: //采用errors包的New方法返回一个err的类型 varerrerror=errors.New("thisisanewerror") //由于已经实现了error接口的方法因此可以直接调用对应的方法 fmt.Println(err.Error()) //方法二: //采用fmt.Errof将string信息转化为error信息并返回 err=fmt.Errorf("%s","theerrortestforfmt.Errorf") fmt.Println(err.Error()) //方法三: //采用自定义的方式实现一个error的一个duck类型 err=&Customerror{ infoa:"errinfoa", infob:"errinfob", Err:errors.New("testcustomerr"), } fmt.Println(err.Error()) } /*output: thisisanewerror theerrortestforfmt.Errorf infoa:errinfoa,infob:errinfob,originalerrinfo:testcustomerr */

golang中的errorpackage内容也比较简单,这个package中实现了error中所声明的method(Error)相当于是一个error接口的duck类型。

//Packageerrorsimplementsfunctionstomanipulateerrors. packageerrors //Newreturnsanerrorthatformatsasthegiventext. funcNew(textstring)error{ return&errorString{text} } //errorStringisatrivialimplementationoferror. typeerrorStringstruct{ sstring } func(e*errorString)Error()string{ returne.s }

采用fmt.Errorf方法把string类型转化为error类型,在这个方法的内部,先调用fmt包中的Sprintf方法把格式化的输入转化为字符串,在使用errors.New方法返回error类型。

采用自定义的error类型可以先判断err的动态类型,再进行下一层的判断。

比如net.Error接口,是一个对原先error接口的再封装。在读取文件的时候判断读取器读取结束的时候的io.EOF。 //io.EOF varEOF=errors.New("EOF") //net.Error typeErrorinterface{ error Timeout()bool//Istheerroratimeout? Temporary()bool//Istheerrortemporary? }

本文内容总结:

原文链接:https://www.cnblogs.com/Goden/p/4601598.html