goerror-handling

How do we combine multiple error strings in Golang?


I am new to golang, my application needs to return multiple errors in a loop, later requires to be combined and returned as a single error string. I am not able to use the string functions to combine the error messages. What methods can be use to combine these errors into a single error before returning?

package main

import (
   "fmt"
   "strings"
)

func Servreturn() (err error) {

   err1 = fmt.Errorf("Something else occurred")
   err2 = fmt.Errorf("Something else occurred again")

   // concatenate both errors

   return err3

}

Solution

  • You could use the strings.Join() and append() function to acheive this slice.

    example: golang playgorund

    package main
    
    import (
        "fmt"
        "strings"
        "syscall"
    )
    
    func main() {
    
        // create a slice for the errors
        var errstrings []string 
    
        // first error
        err1 := fmt.Errorf("First error:server error")
        errstrings = append(errstrings, err1.Error())
    
        // do something 
        err2 := fmt.Errorf("Second error:%s", syscall.ENOPKG.Error())
        errstrings = append(errstrings, err2.Error())
    
        // do something else
        err3 := fmt.Errorf("Third error:%s", syscall.ENOTCONN.Error())
        errstrings = append(errstrings, err3.Error())
    
        // combine and print all the error
        fmt.Println(fmt.Errorf(strings.Join(errstrings, "\n")))
    
    
    }
    

    This would output a single string which you can send back to the client.

    First error:server1 
    Second error:Package not installed 
    Third error:Socket is not connected
    

    hope this helps!