比较使用 Error.Is 函数的动态错误消息。

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

Compare dynamic error message using Error.Is function

问题

我有一个动态错误消息的例子

metadata.name: invalid value "test-value"

"test-value"将是动态的,如果出现这种错误模式,我需要做一些处理

如何使用Error.Is函数检查错误模式?

英文:

I have a dynamic error message for example

metadata.name: invalid value "test-value"

"test-value" will be dynamic, and I need to do something if this error pattern appears

How to check the errors pattern with Error.Is function?

答案1

得分: 1

你说你的错误消息是动态的。我认为你的意思是你正在定义一个满足error接口的类型。(如果你使用的是fmt.Errorf,那么你应该为这种情况定义一个类型)。

type invalidValueError struct {
  value string
}

func (e *invalidValidError) Error() string {
  return fmt.Sprintf("invalid value %q", e.value)
}

你可以使用errors.As来检查任何给定的错误是否具有这种类型。这不仅会匹配错误本身,还会匹配任何包装的错误。

if ive := (*invalidValueError)(nil); errors.As(err, &ive) {
  // 得到一个*invalidValueError
}

尽量避免匹配错误消息的文本。它们可能会在不同的系统或不同的语言环境下发生变化,并且通常不受兼容性承诺的保证。

英文:

You say your error has a dynamic message. I think you mean that you're defining a type that satisfies the error interface. (If you're using fmt.Errorf instead though, you should define a type for this use case).

type invalidValueError struct {
  value string
}

func (e *invalidValidError) Error() string {
  return fmt.Sprintf("invalid value %q", e.value)
}

You can check whether any given error has this type using errors.As. This will match not only the error itself, but any errors it's wrapping.

if ive := (*invalidValueError)(nil); errors.As(err, &ive) {
  // got an *invalidValueError
}

Avoid matching the text of error messages if at all possible. They can change on different systems or in different locales, and they're generally not covered by compatibility promises.

huangapple
  • 本文由 发表于 2021年8月4日 17:12:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/68648564.html
匿名

发表评论

匿名网友

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

确定