cannot convert (type string) to type errorString

Issue

I wrote a simple program which does executing uptime command and fetch its result. As part of error handling I am getting trouble while converting error type into string and string type to error. How can I achieve this ?

package main

import (
  "fmt"
  "os/exec"
)

type errorString struct {
    s string
  }

func (e *errorString) Error() string {
  return e.s
}

func execCommand(cmd string) (string, error) {
  if cmd == "" {
    return "", &errorString("Passed empty input")
  }

  output, err := exec.Command(cmd).Output()
  fmt.Println("Output: " ,string(output))
  fmt.Println("Error: ", err)
  if err != nil {
    fmt.Printf("Received error %q while executing the command %q", err, cmd)
    return "",err
  }
  fmt.Printf("Command executed successfully.\nOutput: %s\n",output)
  return string(output), nil
}

func main() {

  command := "uptime"
  output, err := execCommand(command)
  if err != nil {
    fmt.Errorf("Received error while executing the command\n")
  } else {
    fmt.Printf("Command %s output %s ", command, output)
  }
}

And while executing getting below error

agastya in uptime_cmd on   my-code-go
❯  go run execute_uptime_command_1.go
# command-line-arguments
./execute_uptime_command_1.go:18:28: cannot convert "Passed empty input" (type string) to type errorString
agastya in uptime_cmd on   my-code-go

What I am trying to achieve is, trying to convert a string into error and vice versa. I am trying to implement below test cases to above code

package main
import (
  "testing"
  "strings"
)

func TestExecCommand(t *testing.T) {

  command := "uptime"
  expectedIncludes := "load"
  received, err := execCommand(command)
  if !strings.Contains(received, expectedIncludes) {
    t.Errorf("Expecting %q to include %q", received, expectedIncludes)
  }

  received, err = execCommand("")
  if received != "" {
    t.Errorf("Expecting empty response when command is empty")
  }

  received, err = execCommand("uptime1")
  if !strings.Contains(string(err), "executable file not found in $PATH") {
    t.Errorf("Expecting executable not found error while executing invalid command as 'uptime1'");
  }
}

And Unable to proceed with above error. Any suggestions much appreicated. It dont have to be explicit solution, even reference articles are fine.

Thank you.

Solution

To create an error from string use

return "", &errorString{"Passed empty input"}

Answered By – Daniyal Ishfaq

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.