go中预定义errors

在GO中预定义的errors成为sentinel error。该名称表示计算机编程中使用一个特定值表示不可能进行进一步处理的做法。如下面的定义

// EOF is the error returned by Read when no more input is available.
// (Read must return EOF itself, not an error wrapping EOF,
// because callers will test for EOF using ==.)
// Functions should return EOF only to signal a graceful end of input.
// If the EOF occurs unexpectedly in a structured data stream,
// the appropriate error is either ErrUnexpectedEOF or some other error
// giving more detail.
var EOF = errors.New("EOF")
复制代码

使用sentinel error,调用者必须使用==将结果与预先声明的值进行比较。如果返回error是经过了封装或者添加了其他信息后,就破坏了调用者的==

You should only handle errors once. Handling an error means inspecting the error value and making a single decision.

但是记录错误的日志和返回error不同时进行,可以使用wrap errors,一种是第三方库,另外就是

如果日志与错误无关,并且对调试没有帮助,可以认为噪音。
如对http的接口记录,谁调用了一个什么接口做了什么事,可以任务对以后的调试是有帮助的。

github.com/pkg/error
wrap errors 包装根因、cause 获取根因
%+v, err打印原始错误堆栈信息

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享