Go – Handle Errors Conditionally

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

Go - Handle Errors Conditionally

问题

我有一个代码,在其中克隆多个GitLab仓库。我依赖的库是"gopkg.in/src-d/go-git.v4"。如果仓库已经存在,克隆函数将返回一个错误。

我想忽略这个错误,并继续循环克隆仓库。下面是我尝试使用errors.New()解决这个问题的代码。然而,它不起作用,因为返回的err和新的错误不匹配。

import (
   gitgo "gopkg.in/src-d/go-git.v4"
   "log"
   "errors"
)

var errRepoIsThere = errors.New("repository already exists")

_, err := gitgo.PlainClone(repoLocalPath, false, &gitgo.CloneOptions{})

if !errors.Is(err, errRepoIsThere) {
	  log.Fatal(err)
}

gitgo.PlainClone返回的错误如下所定义:

https://pkg.go.dev/github.com/go-git/go-git/v5#pkg-variables

ErrRepositoryNotExists = errors.New("repository does not exist")

我查看了这个问题https://stackoverflow.com/questions/39121172/how-to-compare-go-errors,并看到所有的答案都不鼓励使用err.Error() == err2.Error()这种类型的错误处理。

在这种情况下,对于我的问题,什么是正确的方法呢?

英文:

I have a code where I clone multiple gitlab repositories. The library I am depending on is "gopkg.in/src-d/go-git.v4". The clone function will return an error if a repository already exists.

I want to ignore this error and continue the loop of clonning repoistories. Below is my attempt to solve the issue by using errors.New() However, it does not work since the returned err and the new error do not match.

import (
   gitgo "gopkg.in/src-d/go-git.v4"
   "log"
   "errors"

)

var errRepoIsThere = errors.New("repository already exists")

_, err := gitgo.PlainClone(repoLocalPath, false, &gitgo.CloneOptions{})


if !errors.Is(err, errRepoIsThere) {
	  log.Fatal(err)
	
}

the error returned from gitgo.PlainClone is as defined here:

https://pkg.go.dev/github.com/go-git/go-git/v5#pkg-variables

ErrRepositoryNotExists = errors.New("repository does not exist")

I've went through this question
https://stackoverflow.com/questions/39121172/how-to-compare-go-errors and saw that all awnsers discourage the use of err.Error() == err2.Error() type of error handling.

What would be the right approach for my issue in this case?

答案1

得分: 2

那个错误是一个包级别的变量,本质上是一个单例,所以比较是合适的:

err == gitgo.ErrRepositoryNotExists

比较.Error()被认为是不好的做法,因为错误文本是次要的(但是包的导出被认为是可靠的)。

英文:

That error is a package level var - essentially, a singleton - so comparison is appropriate:

err == gitgo.ErrRepositoryNotExists

Comparing .Error() is considered poor practice because error text is incidental (but package exports are assumed reliable)

huangapple
  • 本文由 发表于 2021年10月6日 07:44:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/69458371.html
匿名

发表评论

匿名网友

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

确定