Go语言没有异常机制, 引入了一个关于错误处理的标准模式,即 error 接口

  1. type error interface {
  2. Error() string
  3. }

1 返回error

  1. func Foo(param int)(n int, err error) {
  2. // ...
  3. // 可以通过errors.New()来创建error实例
  4. return nil, errors.New("出错了")
  5. }
  6. func main() {
  7. n, err := Foo(0) // 调用时的代码建议按如下方式处理错误情况:
  8. if err != nil {
  9. fmt.Println(err)
  10. return
  11. }
  12. // ...
  13. }

2 自定义Error

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. )
  7. type PathError struct {
  8. path string
  9. op string
  10. createTime string
  11. message string
  12. }
  13. // 定义Error方法, 就实现了error接口
  14. func (p *PathError) Error() string {
  15. return fmt.Sprintf("path=%s \nop=%s \ncreateTime=%s \nmessage=%s", p.path,
  16. p.op, p.createTime, p.message)
  17. }
  18. func Open(filename string) error {
  19. file, err := os.Open(filename)
  20. if err != nil {
  21. return &PathError{
  22. path: filename,
  23. op: "read",
  24. message: err.Error(),
  25. createTime: fmt.Sprintf("%v", time.Now()),
  26. }
  27. }
  28. defer file.Close()
  29. return nil
  30. }
  31. func main() {
  32. err := Open("/Users/5lmh/Desktop/go/src/test.txt")
  33. switch v := err.(type) {
  34. case *PathError:
  35. fmt.Println("get path error,", v)
  36. default:
  37. }
  38. }