Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint) #435

Open
wwcchh0123 opened this issue Nov 8, 2024 · 0 comments

Comments

@wwcchh0123
Copy link
Contributor

lint 解释

  • 该 lint 出现是由于进行错误比较时的使用不当。在 Go 语言中处理错误时,特别是涉及到包装错误时,使用 == 来比较错误可能会导致错误的结果,因为它检查的是指针的相等性,而不是错误的实际内容。这意味着如果你有一个错误被包装或是通过某种方式创建的新实例,即使它们表示相同的错误,== 也可能返回 false。
  • 为了正确比较错误,应该使用 errors.Is()errors.Is() 是 Go 语言中用于错误处理的一个函数,用于检查一个错误是否匹配某个特定的错误或是否在错误链中。

错误示例

var ErrNotFound = errors.New("not found")

func someFunction() error {
    // 模拟一个错误
    return fmt.Errorf("发生了一个错误: %w", ErrNotFound)
}

func main() {
    err := someFunction()
    
    // 错误的方式: 使用 ==
    if err == ErrNotFound {
        // err 已经被someFunction()包装过,并且为创建的新实例,因此判断会失效
    }
}

正确示例

    if errors.Is(err, ErrNotFound) {
        // 错误是 ErrNotFound 类型"
    } else {
        // 错误不是 ErrNotFound 类型"
    }
@wwcchh0123 wwcchh0123 changed the title comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint) comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint) Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant