Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

错误处理

gf框架提供了强大、丰富的错误处理能力,由gerror模块实现。

...

https://godoc.org/github.com/gogf/gf/errors/gerror

错误堆栈

标准库的error错误实现比较简单,无法进行堆栈追溯,对于产生错误时的上层调用者来讲不是很友好,无法获得错误的调用链详细信息。gerror支持错误堆栈记录,通过New/NewfWrap/Wrapf均会自动记录当前错误产生时的堆栈信息。

...

可以看到,调用端可以通过Wrap方法将底层的错误信息进行层级叠加,并且包含完整的错误堆栈信息。

fmt格式化

通过以上示例我们可以看到,通过%+v的打印格式可以打印出完整的堆栈信息,当然gerror.Error对象支持多种fmt格式:

...

 %s: api calling failed: adding failed: sql error
%-s: api calling failed
%+s:
1. api calling failed
   1).  main.main
        /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go:14
2. adding failed
   1).  main.main
        /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go:13
3. sql error

Stack方法

func Stack(err error) string

...

1. api calling failed
   1).  main.main
        /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go:14
2. adding failed
   1).  main.main
        /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go:13
3. sql error

Current方法

func Current(err error) error

...

api calling failed: adding failed: sql error
api calling failed

Next方法

func Next(err error) error

...

api calling failed: adding failed: sql error
adding failed: sql error
sql error

Cause方法

func Cause(err error) error

...

执行后,终端输出:

permission denied

日志输出支持

glog日志管理模块天然支持对gerror错误堆栈打印支持,这种支持不是强耦合性的,而是通过fmt格式化打印接口支持的。

...