error

command
v0.0.0-...-73c7131 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 28, 2020 License: Apache-2.0 Imports: 3 Imported by: 0

README

错误

错误的五种常见方法:

  1. 向上传递错误信息(编写库包)
  2. 结束程序 (一般常用在main包中)
  3. 重试
  4. 打印错误日志
  5. 忽略错误

库函数中推荐的做法是使用特性来提供详细的异常信息

Golang 语言中的error接口

type error interface {
    Error() string
}

os 包中的自定义错误类型

type PathError struct {
    Op string // open unlink 等对文件的操作
    Path string // 相关的文件路径
    Err error // 由系统调用返回
}

func (e *PathError) Error() string {
    return e.Op + " " + e.Path + ": " + e.Err.error
}
// 报错示例: open /etc/passwx: no such file or directory
使用自定义错误来处理问题的一个示例
    for try := 0; try < 2; try++ {
        file, err := os.Create(filename)
    if err == nil {
        return
    }
    if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {
        fmt.Println("删除磁盘临时文件") // 恢复一些空间。
        continue
    }
        fmt.Println(file.Name())
    }

panic

发生致命错误要终止程序执行的情况下使用 panic 当 panic 被调用后,程序会立即终止当前函数执行,并开始回溯GO协程的栈,运行任何被推迟的函数

var user = os.Getenv("USER")
if user == "" {
    panic("no user for use")
}

recover

end

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL