Files
build-web-application-with-…/11.1.md
xiemengjun 48addcce49 error处理
2012-11-04 22:27:21 +08:00

64 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 11.1 错误处理
Go语言设计的时候主要的特点是简洁、明白简洁是指语法和C类似相当的简单明白是指任何语句都是很明显的不含有任何隐式的东西Go在设计错误的时候也是一样。我们知道C语言里面返回错误是使用-1或者nil之类的返回信息表示错误但是对于使用者来说这个返回值根本不知道什么意思而Go里面当发生异常时返回一个Error类型通过前面编写的代码我们发现在Go语言里面有很多地方都使用了Error类型很多函数都有这个Error返回。例如`os.Open`函数当打开文件失败时返回一个不为nil的error
func Open(name string) (file *File, err error)
下面这个例子通过`os.Open`打开一个文件,如果出错那么会执行`log.Fatal`打印出来错误信息:
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
其实这样的error返回在Go语言的很多内置包里面有很多我们这个小节将详细的介绍这些error是怎么设计的以及在我们设计的Web应用如何更好的处理error。
## Error类型
error类型是一个接口类型这是它的定义
type error interface {
Error() string
}
error是一个内置的类型变量我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的非导出结构errorString
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
你可以通过`errors.New`把一个字符串转化为errorString然后返回error接口其内部实现如下
// New returns an error that formats as the given text.
func New(text string) error {
return &errorString{text}
}
下面这个例子演示了如何使用`errors.New`:
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("math: square root of negative number")
}
// implementation
}
我们在调用的地方可以这样处理错误:
f, err := Sqrt(-1)
if err != nil {
fmt.Println(err)
}
## 自定义Error
## Error检测
## 总结
## links
* [目录](<preface.md>)
* 上一节: [错误处理,调试和测试](<11.md>)
* 下一节: [使用GDB调试](<11.2.md>)