从库包返回错误的类型

huangapple go评论96阅读模式
英文:

returning type of errors from library packages

问题

在https://github.com/golang/go/wiki/Errors中提到,

调用代码可以通过使用类型切换来测试特定类型的error

在https://github.com/golang/go/wiki/ErrorValueFAQ中提到,

如果你目前使用==比较错误,请改用errors.Is
if errors.Is(err, io.ErrUnexpectedEOF)

然而,我一直没有找到如何从我的库包中返回这种类型的错误,以便我的包使用者可以进行错误检查,例如

  • if errors.Is(err, io.ErrUnexpectedEOF)
  • if errors.As(err, &e)

请帮忙。

PS. 上述问题是基于以下初始问题提出的:

https://stackoverflow.com/questions/68518752/go-latest-idiomatic-error-reporting-approach-from-library-packages

而对于这两个问题的最佳答案是--
https://blog.golang.org/go1.13-errors

英文:

In https://github.com/golang/go/wiki/Errors it says,

> Calling code would test for a special type of error by using a type switch

In https://github.com/golang/go/wiki/ErrorValueFAQ it says,

> If you currently compare errors using ==, use errors.Is instead
> if errors.Is(err, io.ErrUnexpectedEOF)

However, I haven't been able to figure out how to return such kind of errors from my library packages, so that my package consumers can do error checkings like

  • if errors.Is(err, io.ErrUnexpectedEOF)
  • if errors.As(err, &e)

Please help.

PS. the above question was made possible because of the following initial question:

https://stackoverflow.com/questions/68518752/go-latest-idiomatic-error-reporting-approach-from-library-packages

And the best answer to both questions is --
https://blog.golang.org/go1.13-errors

答案1

得分: 1

根据errors包的文档所解释的:

UnwrapIsAs函数适用于可能包装其他错误的错误。

因此,关键是为您的错误类型实现Unwrap。可以通过以下方式之一实现:

  • 使用fmt.Errorf%w
return fmt.Errorf("Some error: %w", io.ErrUnexpectedEOF)

返回的错误会包装意外的EOF错误,因此可以使用errors.Iserrors.As进行解包。

  • 使用自定义类型:
type MyErr struct {
  ...
  err error
}

func (err MyErr) Error() string {...}
func (err MyErr) Unwrap() error {return err.err}

然后:

return MyErr{err: io.ErrUnexpectedEOF}

这样也会解包以获取意外的EOF。

英文:

As explained in the errors package documentation:

> The Unwrap, Is and As functions work on errors that may wrap other errors.

So the key is to implement Unwrap for your error types. This can be done in one of the following ways:

  • Use fmt.Errorf with %w
return fmt.Errorf("Some error: %w",io.ErrUnexpectedEOF)

The returned error wraps the unexpected EOF error, so errors.Is and errors.As can unwrap it.

  • Use a custom type:
type MyErrr struct {
 ...
  err error
}

func (err MyErr) Error() string {...}
func (err MyErr) Unwrap() error {return err.err}

Then:

return MyError{err:io.ErrUnexpectedEOF}

This will also be unwrapped to get the unexpected EOF.

huangapple
  • 本文由 发表于 2021年8月2日 03:47:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68613849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定