简化Golang中的重复开关案例

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

Simplify recurring switch cases in golang

问题

我正在尝试理解是否有更好的方法来简化在golang中重复的switch case。我有一个方法可以返回多个错误,但我只对其中的3个特定错误感兴趣,我需要返回一个特定的注释错误而不是通用错误。然而,case1、case2返回err1、err2,但是在case3的情况下,我需要使用不同的参数调用相同的方法,并处理方法返回的err1、err2。如果你有任何建议,请提供。目前,我是按照下面的方式处理,但我想看看是否可以简化调用case1、case2的重复性。

_, err := doSomething(var1)
if err != nil {
    switch err.Error() {
    case case1:
        return err1
    case case2:
        return err2
    case case3:
        _, err := doSomething(var2)
        switch err.Error() {
        case case1:
            return err1
        case case2:
            return err2
        default:
            return err
        }
    default:
        return err
    }
}

如果需要更多细节或对问题本身需要更多澄清,请告诉我。

提前感谢。

英文:

I am trying to understand if there is a better way to simplify recurring switch cases in golang. I have a method that can return multiple errors, but I am interested in 3 specific errors where I need to return a specific annotated error than the generic error. However case1, case2 return err1, err2 But incase of case3 I need to call the same method with different parameters and also handle if the method return err1, err2. Please provide any suggestions if you have. Currently I am handling in the below way but trying to see if I can simplify the repetitiveness of calling case1, case2.

    _, err := doSomething(var1)
	if err != nil {
		switch err.Error() {
		case case1:
			return err1
		case case2:
			return err2
		case case3:
			_, err := doSomething(var2)
			switch err.Error() {
			case case1:
				return err1
			case case2:
				return err2
			default:
				return err
			}
		default:
			return err

Please let me know if you need more details or needs more clarification on my question itself.

Thanks in advance.

答案1

得分: 6

将特殊情况的错误进行翻译,并继续常规处理。

_, err := doSomething(var1)
if err != nil {
	if err.Error() == case3 {
		_, err = doSomething(var2)
	}
	switch err.Error() {
	case case1:
		return err1
	case case2:
		return err2
	default:
		return err
	}
}
英文:

Translate the error for the special case. Continue on to the common handling.

_, err := doSomething(var1)
if err != nil {
	if err.Error() == case3 {
		_, err = doSomething(var2)
	}
	switch err.Error() {
	case case1:
		return err1
	case case2:
		return err2
	default:
		return err
	}
}

huangapple
  • 本文由 发表于 2022年1月17日 02:08:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/70732787.html
匿名

发表评论

匿名网友

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

确定