user3435964
user3435964

Reputation: 949

Simplify recurring switch cases in golang

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.

Upvotes: 2

Views: 155

Answers (1)

Strega
Strega

Reputation: 96

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
    }
}

Upvotes: 6

Related Questions