errors.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package cmd
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "github.com/fatih/color"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/api/types"
  9. )
  10. var ErrNotLoggedIn error = errors.New("You are not logged in.")
  11. var ErrCannotConnect error = errors.New("Unable to connect to the Porter server.")
  12. func checkLoginAndRun(args []string, runner func(user *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error) error {
  13. client := GetAPIClient(config)
  14. user, err := client.AuthCheck(context.Background())
  15. if err != nil {
  16. red := color.New(color.FgRed)
  17. if strings.Contains(err.Error(), "Forbidden") {
  18. red.Print("You are not logged in. Log in using \"porter auth login\"\n")
  19. return ErrNotLoggedIn
  20. } else if strings.Contains(err.Error(), "connection refused") {
  21. red.Printf("Unable to connect to the Porter server at %s\n", config.Host)
  22. red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
  23. red.Print("To start a local server, run \"porter server start\"\n")
  24. return ErrCannotConnect
  25. }
  26. red.Printf("Error: %v\n", err.Error())
  27. return err
  28. }
  29. err = runner(user, client, args)
  30. if err != nil {
  31. red := color.New(color.FgRed)
  32. if strings.Contains(err.Error(), "403") {
  33. red.Print("You do not have the necessary permissions to view this resource")
  34. return nil
  35. } else if strings.Contains(err.Error(), "connection refused") {
  36. red.Printf("Unable to connect to the Porter server at %s\n", config.Host)
  37. red.Print("To set a different host, run \"porter config set-host [HOST]\"")
  38. red.Print("To start a local server, run \"porter server start\"")
  39. return nil
  40. }
  41. red.Printf("Error: %v\n", err.Error())
  42. return err
  43. }
  44. return nil
  45. }