Go error实践


本文摘自网络,作者,侵删。

1. Go原生error

Go原生的error是一个接口类型,只要实现Error()方法就是一个error。

type error interface {
	Error() string}复制代码

一般我们使用errors.New()来生成一个error,注意这个方法返回的每个error都是不同的,即使表示错误的字符串是完全相同的,因为这个方法返回的是error的对象指针

// New returns an error that formats as the given text.// Each call to New returns a distinct error value even if the text is identical.func New(text string) error {	return &errorString{text}//这里有个知识点,就是结构体初始化的三种方式与异同,可以参考[Ref 1](#Ref)}// errorString is a trivial implementation of error.type errorString struct {
	s string}func (e *errorString) Error() string {	return e.s
}复制代码

2. Error和Exception

Go中不存在Exception,而是支持多参数返回中包含Error。通过多参数和简单的约定,Go让程序员知道了什么时候出现了问题,并通过保留panic来反馈真正的异常。

defer 与 recovery()


本文来自:51CTO博客

感谢作者:mb600bea0083c0f

查看原文:Go error实践

相关阅读 >>

手撸Golang 行为型设计模式 命令模式

我的个人能力发展报告(2015-2019)

Golang 类似php中 http_build_query 方法

手撸Golang etcd raft协议之2

分享5种文件变更时自动重载Go程序的方法

Golang map需要make吗

Golang- Go语言学习笔记之定义变量

Go-map

protoc Go插件编写之四 (实现生成自己的proto文件)

Go-struct

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...