当前位置:网站首页>GO语言-自定义error
GO语言-自定义error
2022-06-23 03:56:00 【一边学习一边哭】
目录
前言
error是go语言中的一种数据类型,内置接口。定义了一个方法Error() string
error接口

error接口的实现--errorString结构体,实现Error方法。

内置包创建错误对象
go语言内置的errors包下的New()函数和fmt包下的Errorf(),都可以创建一个error对象。
func main() {
err1 := errors.New("通过errors.New()创建的错误")
fmt.Printf("err1:%v, 类型:%T\n", err1, err1)
err2 := fmt.Errorf("通过fmt.Errorf()创建的错误")
fmt.Printf("err2:%v, 类型:%T\n", err2, err2)
}
自定义error接口的实现
从前言中可以看出来,error接口十分简单。要实现error接口,只需要自定义一个结构体,实现Error()方法即可。
下面我们就自定义实现一下errror接口。函数输入年龄的值进行判断,过大过小都进行报错。
type AgeError struct {
msg string
age int
}
func (a *AgeError) Error() string {
return a.msg + ", 年龄是:" + strconv.Itoa(a.age)
}
func main() {
age, err := ageVerification(200)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(age)
}
}
func ageVerification(age int) (int, error) {
if age > 150 || age < 0 {
return age, &AgeError{"年龄不合法", age}
}
return age, nil
}![]()
边栏推荐
- Event log keyword: eventlogtags logtags
- Seata四大模式之XA模式详解及代码实现
- Open source ecology 𞓜 super practical open source license basic knowledge literacy post (Part 2)
- Mysql入门学习(二)之子查询+关联
- Onnxoptimizer, onnxsim usage records
- APP自动化测试-Appium进阶
- Difficult to find a job in a bad environment? Ali on three sides. Fortunately, he has made full preparations and has offered
- onnxoptimizer、onnxsim使用记录
- MCS: discrete random variable - uniform distribution
- 架构师之路,从「存储选型」起步
猜你喜欢
随机推荐
I have been engaged in software testing for 5 years and have changed jobs for 3 times. I have understood the field of software testing
Event日志关键字:EventLogTags.logtags
第九章 APP项目测试(1)
IDEA 代码开发完毕后,提交代码,提交后发现分支不对,怎么撤回
STM32cube 串口使用DMA+IDLE接收不定长数据
树莓派网络远程访问
架构师之路,从「存储选型」起步
Open source ecology 𞓜 super practical open source license basic knowledge literacy post (Part 2)
[laravel series 7.8] broadcasting system
奇门遁甲辅助决策软件
MySQL自定义序列数的实现
渗透测试基础 | 附带测试点、测试场景
Array The from method creates an undefined array of length n
APP自动化测试-Appium进阶
(IntelliJ) plug in background image plus
搭建一套 gocd 的环境
What is the average annual salary of an outsourced tester who has worked for 5-8 years?
Jetpack Compose 从开门到入门之 MenuBar桌面菜单(Desktop Menu)
Arduino temperature and humidity sensor DHT11 (including code)
Post processing of multisensor data fusion using Px4 ECL








