当前位置:网站首页>Go language - custom error
Go language - custom error
2022-06-23 05:27:00 【Crying while learning】
Catalog
Built in package creation error object
Customize error Interface implementation
Preface
error yes go A data type in a language , Built in interface . Defines a method Error() string
error Interface

error Interface implementation --errorString Structure , Realization Error Method .

Built in package creation error object
go Language built in errors Under bag New() Functions and fmt Under bag Errorf(), You can create one of them error object .
func main() {
err1 := errors.New(" adopt errors.New() Error creating ")
fmt.Printf("err1:%v, type :%T\n", err1, err1)
err2 := fmt.Errorf(" adopt fmt.Errorf() Error creating ")
fmt.Printf("err2:%v, type :%T\n", err2, err2)
}
Customize error Interface implementation
It can be seen from the previous words ,error The interface is very simple . To achieve error Interface , Just customize a structure , Realization Error() The method can .
Let's customize the implementation errror Interface . Function input the value of age to judge , An error is reported when the size is too large or too small .
type AgeError struct {
msg string
age int
}
func (a *AgeError) Error() string {
return a.msg + ", Age is :" + 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 is illegal ", age}
}
return age, nil
}![]()
边栏推荐
- Missing essential plugin
- 软件项目管理 8.4.软件项目质量计划
- JDBC introductory learning (II) encapsulation tool class
- [leetcode] longest increasing subsequence problem and its application
- MCS:连续随机变量——Student’s t分布
- 今日睡眠质量记录80分
- MCS: discrete random variable Bernoulli distribution
- Web 应用程序安全测试指南
- Event log keyword: eventlogtags logtags
- Image noise reduction denoise AI
猜你喜欢
随机推荐
IDEA 代码开发完毕后,提交代码,提交后发现分支不对,怎么撤回
Introduction to JDBC (I) DML operation
如何进行探索性数据分析
Laravel8 implementation of picture verification code
[microservices | Nacos] list of issues related to the Nacos version
面对新的挑战,成为更好的自己--进击的技术er
弱者易怒如虎,强者平静如水,真正厉害的人早已戒掉了情绪
MCS: continuous random variable lognormal distribution
【Leetcode】最长递增子序列问题及应用
Drama asking Huamen restaurant Weng
The tiobe programming language ranking is an indicator of the popular trend of programming languages
Zygote process
insert into... Where not exists insert to avoid repeated use
JDBC入门学习(三)之事务回滚功能的实现
Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
李宏毅《机器学习》丨5. Tips for neural network design(神经网络设计技巧)
(IntelliJ)插件一 Background Image Plus
Win软件 - (Net-Framework)已处理证书链,但是在不受信任提供程序信任的根证书中终止
Introduction to JDBC (IV) - use of Druid connection pool
第十六届东北地区大学生程序设计竞赛(热身赛)B-String Value(字符串dp)









