Repository: supabase/cli
Pull request #1746 (2023-12-12 15:35:00)

feat: `--create-ticket` flag to send error reports to sentry
## What kind of change does this PR introduce?

feature

## What is the new behavior?

Reports error to sentry when any commands are with `--create-ticket` flag. Helps to collect diagnostics information.
- [x] server side rate limiting
- [x] add stacktrace to all errors

Going forward, any errors from external packages should be wrapped in `errors.New(err)` using [go-errors](https://github.com/go-errors/errors).

## Additional context

Eg: https://supabase.sentry.io/issues/4734608486/events/e250b9cc83c245d1aa520f1e3ece5017


notion-workspace[bot]: [Integrate sentry sdk](https://www.notion.so/Integrate-sentry-sdk-d1ff51809f554cbba30ea100bc04becc?pvs=8&n=github_linkback)
soedirgo: Telemetry is a [very](https://news.ycombinator.com/item?id=34707583) [sensitive](https://news.ycombinator.com/item?id=35974653) [topic](https://news.ycombinator.com/item?id=27727150), even for anonymous info. IMO we should make this opt-in by prompting on first run instead of opt-out. 

Patch:
diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml
index b68d17ad..21bdac0c 100644
--- a/.github/workflows/release-beta.yml
+++ b/.github/workflows/release-beta.yml
@@ -50,6 +50,7 @@ jobs:
           GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
           BREWTAP_TOKEN: ${{ secrets.GH_PAT }}
           SCOOP_TOKEN: ${{ secrets.GH_PAT }}
+          SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
 
       - run: gh release edit v${{ needs.release.outputs.new-release-version }} --draft=false --prerelease
         env:
diff --git a/.goreleaser.yml b/.goreleaser.yml
index 89d06082..9c5e10b4 100644
--- a/.goreleaser.yml
+++ b/.goreleaser.yml
@@ -5,7 +5,7 @@ builds:
     flags:
       - -trimpath
     ldflags:
-      - -s -w -X github.com/supabase/cli/internal/utils.Version={{.Version}}
+      - -s -w -X github.com/supabase/cli/internal/utils.Version={{.Version}} -X github.com/supabase/cli/internal/utils.SentryDsn={{ .Env.SENTRY_DSN }}
     env:
       - CGO_ENABLED=0
     targets:
diff --git a/cmd/login.go b/cmd/login.go
index cf5d49d5..d62b7b3d 100644
--- a/cmd/login.go
+++ b/cmd/login.go
@@ -2,7 +2,6 @@ package cmd
 
 import (
 	"bytes"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -10,6 +9,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/google/uuid"
 	"github.com/mattn/go-isatty"
 	"github.com/spf13/afero"
@@ -20,18 +20,18 @@ import (
 )
 
 var (
-	ErrMissingToken = errors.New("Cannot use automatic login flow inside non-TTY environments. Please provide " + utils.Aqua("--token") + " flag or set the " + utils.Aqua("SUPABASE_ACCESS_TOKEN") + " environment variable.")
+	ErrMissingToken = errors.Errorf("Cannot use automatic login flow inside non-TTY environments. Please provide %s flag or set the %s environment variable.", utils.Aqua("--token"), utils.Aqua("SUPABASE_ACCESS_TOKEN"))
 )
 
 func generateTokenName() (string, error) {
 	user, err := user.Current()
 	if err != nil {
-		return "", fmt.Errorf("cannot retrieve username: %w", err)
+		return "", errors.Errorf("cannot retrieve username: %w", err)
 	}
 
 	hostname, err := os.Hostname()
 	if err != nil {
-		return "", fmt.Errorf("cannot retrieve hostname: %w", err)
+		return "", errors.Errorf("cannot retrieve hostname: %w", err)
 	}
 
 	return fmt.Sprintf("cli_%s@%s_%d", user.Username, hostname, time.Now().Unix()), nil
@@ -58,7 +58,7 @@ var (
 			} else if cmd.Flags().Changed("token") {
 				token, err := cmd.Flags().GetString("token")
 				if err != nil {
-					return fmt.Errorf("cannot parse 'token' flag: %w", err)
+					return errors.Errorf("cannot parse 'token' flag: %w", err)
 				}
 				params.Token = token
 			} else if token := os.Getenv("SUPABASE_ACCESS_TOKEN"); token != "" {
@@ -83,7 +83,7 @@ var (
 			if cmd.Flags().Changed("name") {
 				name, err := cmd.Flags().GetString("name")
 				if err != nil {
-					return fmt.Errorf("cannot parse 'name' flag: %w", err)
+					return errors.Errorf("cannot parse 'name' flag: %w", err)
 				}
 				params.TokenName = name
 			} else {
diff --git a/cmd/root.go b/cmd/root.go
index b8868145..0c18dbc9 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -4,14 +4,19 @@ import (
 	"context"
 	"errors"
 	"fmt"
+	"net"
+	"net/url"
 	"os"
 	"os/signal"
 	"strings"
+	"time"
 
+	"github.com/getsentry/sentry-go"
 	"github.com/mitchellh/mapstructure"
 	"github.com/spf13/afero"
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
+	"github.com/supabase/cli/internal/services"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/flags"
 )
@@ -65,12 +70,24 @@ func IsExperimental(cmd *cobra.Command) bool {
 }
 
 var (
+	sentryOpts = sentry.ClientOptions{
+		Dsn:        utils.SentryDsn,
+		Release:    utils.Version,
+		ServerName: "<redacted>",
+		// Set TracesSampleRate to 1.0 to capture 100%
+		// of transactions for performance monitoring.
+		// We recommend adjusting this value in production,
+		TracesSampleRate: 1.0,
+	}
+
+	createTicket bool
+
 	rootCmd = &cobra.Command{
 		Use:     "supabase",
 		Short:   "Supabase CLI " + utils.Version,
 		Version: utils.Version,
 		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
-			if IsExperimental(cmd) && !viper.GetBool("experimental") {
+			if IsExperimental(cmd) && !viper.GetBool("EXPERIMENTAL") {
 				return errors.New("must set the --experimental flag to run this command")
 			}
 			cmd.SilenceUsage = true
@@ -103,25 +120,59 @@ var (
 				utils.CmdSuggestion = utils.SuggestDebugFlag
 			}
 			cmd.SetContext(ctx)
-			return nil
+			// Setup sentry last to ignore errors from parsing cli flags
+			apiHost, err := url.Parse(utils.GetSupabaseAPIHost())
+			if err != nil {
+				return err
+			}
+			sentryOpts.Environment = apiHost.Host
+			return sentry.Init(sentryOpts)
 		},
 		SilenceErrors: true,
 	}
 )
 
 func Execute() {
+	defer recoverAndExit()
 	if err := rootCmd.Execute(); err != nil {
-		fmt.Fprintln(os.Stderr, utils.Red(err.Error()))
-		if len(utils.CmdSuggestion) > 0 {
-			fmt.Fprintln(os.Stderr, utils.CmdSuggestion)
-		}
-		os.Exit(1)
+		panic(err)
 	}
 	if utils.CmdSuggestion != utils.SuggestDebugFlag {
 		fmt.Fprintln(os.Stderr, utils.CmdSuggestion)
 	}
 }
 
+func recoverAndExit() {
+	err := recover()
+	if err == nil {
+		return
+	}
+	var msg string
+	switch err := err.(type) {
+	case string:
+		msg = err
+	case error:
+		msg = err.Error()
+	default:
+		msg = fmt.Sprintf("%#v", err)
+	}
+	// Log error to console
+	fmt.Fprintln(os.Stderr, utils.Red(msg))
+	if len(utils.CmdSuggestion) > 0 {
+		fmt.Fprintln(os.Stderr, utils.CmdSuggestion)
+	}
+	// Report error to sentry
+	if createTicket && len(utils.SentryDsn) > 0 {
+		sentry.ConfigureScope(addSentryScope)
+		eventId := sentry.CurrentHub().Recover(err)
+		if eventId != nil && sentry.Flush(2*time.Second) {
+			fmt.Fprintln(os.Stderr, "Sent crash report:", *eventId)
+			fmt.Fprintln(os.Stderr, "Quote the crash ID above when filing a bug report: https://github.com/supabase/cli/issues/new/choose")
+		}
+	}
+	os.Exit(1)
+}
+
 func init() {
 	cobra.OnInitialize(func() {
 		// Allow overriding config object with automatic env
@@ -144,6 +195,7 @@ func init() {
 	flags.String("workdir", "", "path to a Supabase project directory")
 	flags.Bool("experimental", false, "enable experimental features")
 	flags.Var(&utils.DNSResolver, "dns-resolver", "lookup domain names using the specified resolver")
+	flags.BoolVar(&createTicket, "create-ticket", false, "create a support ticket for any CLI error")
 	cobra.CheckErr(viper.BindPFlags(flags))
 
 	rootCmd.SetVersionTemplate("{{.Version}}\n")
@@ -167,3 +219,22 @@ func changeWorkDir(fsys afero.Fs) error {
 	}
 	return os.Chdir(workdir)
 }
+
+func addSentryScope(scope *sentry.Scope) {
+	serviceImages := services.GetServiceImages()
+	imageToVersion := make(map[string]interface{}, len(serviceImages))
+	for _, image := range services.GetServiceImages() {
+		parts := strings.Split(image, ":")
+		// Bypasses sentry's IP sanitization rule, ie. 15.1.0.147
+		if net.ParseIP(parts[1]) != nil {
+			imageToVersion[parts[0]] = "v" + parts[1]
+		} else {
+			imageToVersion[parts[0]] = parts[1]
+		}
+	}
+	scope.SetContext("Services", imageToVersion)
+	scope.SetContext("Config", map[string]interface{}{
+		"Image Registry": utils.GetRegistry(),
+		"Project ID":     flags.ProjectRef,
+	})
+}
diff --git a/cmd/sslEnforcement.go b/cmd/sslEnforcement.go
index ec8469d1..7b44d6dd 100644
--- a/cmd/sslEnforcement.go
+++ b/cmd/sslEnforcement.go
@@ -1,8 +1,7 @@
 package cmd
 
 import (
-	"fmt"
-
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/spf13/cobra"
 	"github.com/supabase/cli/internal/ssl_enforcement/get"
@@ -25,7 +24,7 @@ var (
 		Short: "Update SSL enforcement configuration",
 		RunE: func(cmd *cobra.Command, args []string) error {
 			if !dbEnforceSsl && !dbDisableSsl {
-				return fmt.Errorf("enable/disable not specified")
+				return errors.New("enable/disable not specified")
 			}
 			return update.Run(cmd.Context(), flags.ProjectRef, dbEnforceSsl, afero.NewOsFs())
 		},
diff --git a/cmd/sso.go b/cmd/sso.go
index 6151c318..766c749f 100644
--- a/cmd/sso.go
+++ b/cmd/sso.go
@@ -1,8 +1,7 @@
 package cmd
 
 import (
-	"fmt"
-
+	"github.com/go-errors/errors"
 	"github.com/spf13/cobra"
 
 	"github.com/supabase/cli/internal/sso/create"
@@ -66,7 +65,7 @@ var (
 		Example: `  supabase sso remove b5ae62f9-ef1d-4f11-a02b-731c8bbb11e8 --project-ref mwjylndxudmiehsxhmmz`,
 		RunE: func(cmd *cobra.Command, args []string) error {
 			if !utils.UUIDPattern.MatchString(args[0]) {
-				return fmt.Errorf("identity provider ID %q is not a UUID", args[0])
+				return errors.Errorf("identity provider ID %q is not a UUID", args[0])
 			}
 
 			return remove.Run(cmd.Context(), flags.ProjectRef, args[0], ssoOutput.Value)
@@ -81,7 +80,7 @@ var (
 		Example: `  supabase sso update b5ae62f9-ef1d-4f11-a02b-731c8bbb11e8 --project-ref mwjylndxudmiehsxhmmz --add-domains example.com`,
 		RunE: func(cmd *cobra.Command, args []string) error {
 			if !utils.UUIDPattern.MatchString(args[0]) {
-				return fmt.Errorf("identity provider ID %q is not a UUID", args[0])
+				return errors.Errorf("identity provider ID %q is not a UUID", args[0])
 			}
 
 			return update.Run(cmd.Context(), update.RunParams{
@@ -108,7 +107,7 @@ var (
 		Example: `  supabase sso show b5ae62f9-ef1d-4f11-a02b-731c8bbb11e8 --project-ref mwjylndxudmiehsxhmmz`,
 		RunE: func(cmd *cobra.Command, args []string) error {
 			if !utils.UUIDPattern.MatchString(args[0]) {
-				return fmt.Errorf("identity provider ID %q is not a UUID", args[0])
+				return errors.Errorf("identity provider ID %q is not a UUID", args[0])
 			}
 
 			format := ssoOutput.Value
diff --git a/cmd/start.go b/cmd/start.go
index 2e4cc74e..3485f734 100644
--- a/cmd/start.go
+++ b/cmd/start.go
@@ -6,7 +6,6 @@ import (
 	"github.com/spf13/afero"
 	"github.com/spf13/cobra"
 	"github.com/supabase/cli/internal/start"
-	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/flags"
 )
 
@@ -23,11 +22,9 @@ var (
 		RunE: func(cmd *cobra.Command, args []string) error {
 			fsys := afero.NewOsFs()
 			if preview {
-				projectRef, err := utils.LoadProjectRef(fsys)
-				if err != nil {
+				if _, err := flags.LoadProjectRef(fsys); err != nil {
 					return err
 				}
-				flags.ProjectRef = projectRef
 			}
 			return start.Run(cmd.Context(), fsys, excludedContainers, ignoreHealthCheck, flags.ProjectRef)
 		},
diff --git a/go.mod b/go.mod
index 71e6c55f..4893f1fc 100644
--- a/go.mod
+++ b/go.mod
@@ -14,6 +14,8 @@ require (
 	github.com/docker/cli v24.0.7+incompatible
 	github.com/docker/docker v24.0.7+incompatible
 	github.com/docker/go-connections v0.4.0
+	github.com/getsentry/sentry-go v0.25.0
+	github.com/go-errors/errors v1.5.1
 	github.com/go-git/go-git/v5 v5.11.0
 	github.com/go-xmlfmt/xmlfmt v1.1.2
 	github.com/golang-jwt/jwt/v5 v5.2.0
diff --git a/go.sum b/go.sum
index 1c6d5a3b..cabcf6d1 100644
--- a/go.sum
+++ b/go.sum
@@ -149,11 +149,15 @@ github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q
 github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
 github.com/getkin/kin-openapi v0.118.0 h1:z43njxPmJ7TaPpMSCQb7PN0dEYno4tyBPQcrFdHoLuM=
 github.com/getkin/kin-openapi v0.118.0/go.mod h1:l5e9PaFUo9fyLJCPGQeXI2ML8c3P8BHOEV2VaAVf/pc=
+github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI=
+github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY=
 github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
 github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
 github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
 github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
 github.com/gliderlabs/ssh v0.3.5 h1:OcaySEmAQJgyYcArR+gGGTHCyE7nvhEMTlYY+Dp8CpY=
+github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
+github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
 github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
 github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
 github.com/go-git/go-billy/v5 v5.5.0 h1:yEY4yhzCDuMGSv83oGxiBotRzhwhNr8VZyphhiu+mTU=
@@ -452,6 +456,7 @@ github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdU
 github.com/perimeterx/marshmallow v1.1.4/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
 github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=
 github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
+github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
 github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4=
 github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI=
 github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
diff --git a/internal/bans/get/get.go b/internal/bans/get/get.go
index 75527dc7..81744b78 100644
--- a/internal/bans/get/get.go
+++ b/internal/bans/get/get.go
@@ -2,9 +2,9 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -15,14 +15,10 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		resp, err := utils.GetSupabase().GetNetworkBansWithResponse(ctx, projectRef)
 		if err != nil {
-			return fmt.Errorf("failed to retrieve network bans: %w", err)
+			return errors.Errorf("failed to retrieve network bans: %w", err)
 		}
 		if resp.JSON201 == nil {
-			return errors.New("failed to retrieve network bans; received: " + string(resp.Body))
-		}
-
-		if err != nil {
-			return err
+			return errors.New("Unexpected error retrieving network bans: " + string(resp.Body))
 		}
 		fmt.Printf("DB banned IPs: %+v\n", resp.JSON201.BannedIpv4Addresses)
 		return nil
diff --git a/internal/bans/update/update.go b/internal/bans/update/update.go
index 694e12e7..46e3cbca 100644
--- a/internal/bans/update/update.go
+++ b/internal/bans/update/update.go
@@ -2,10 +2,10 @@ package update
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -15,7 +15,7 @@ func validateIps(ips []string) error {
 	for _, ip := range ips {
 		ip := net.ParseIP(ip)
 		if ip.To4() == nil {
-			return fmt.Errorf("only IPv4 supported at the moment: %s", ip)
+			return errors.Errorf("only IPv4 supported at the moment: %s", ip)
 		}
 	}
 	return nil
@@ -36,10 +36,10 @@ func Run(ctx context.Context, projectRef string, dbIpsToUnban []string, fsys afe
 			Ipv4Addresses: dbIpsToUnban,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to remove network bans: %w", err)
 		}
 		if resp.StatusCode() != 200 {
-			return errors.New("failed to remove network bans: " + string(resp.Body))
+			return errors.New("Unexpected error removing network bans: " + string(resp.Body))
 		}
 		fmt.Printf("Successfully removed bans for %+v.\n", dbIpsToUnban)
 		return nil
diff --git a/internal/branches/create/create.go b/internal/branches/create/create.go
index 403e74d9..03be45e9 100644
--- a/internal/branches/create/create.go
+++ b/internal/branches/create/create.go
@@ -2,17 +2,18 @@ package create
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/gen/keys"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 	"github.com/supabase/cli/pkg/api"
 )
 
 func Run(ctx context.Context, name, region string, fsys afero.Fs) error {
-	ref, err := utils.LoadProjectRef(fsys)
+	ref, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
@@ -27,7 +28,7 @@ func Run(ctx context.Context, name, region string, fsys afero.Fs) error {
 		Region:     &region,
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create preview branch: %w", err)
 	}
 
 	if resp.JSON201 == nil {
diff --git a/internal/branches/delete/delete.go b/internal/branches/delete/delete.go
index b552af8a..28c457cb 100644
--- a/internal/branches/delete/delete.go
+++ b/internal/branches/delete/delete.go
@@ -2,17 +2,17 @@ package delete
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
 func Run(ctx context.Context, branchId string) error {
 	resp, err := utils.GetSupabase().DeleteBranchWithResponse(ctx, branchId)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to delete preview branch: %w", err)
 	}
 	if resp.StatusCode() != http.StatusOK {
 		return errors.New("Unexpected error deleting preview branch: " + string(resp.Body))
diff --git a/internal/branches/disable/disable.go b/internal/branches/disable/disable.go
index ce84f6cc..1d313a5a 100644
--- a/internal/branches/disable/disable.go
+++ b/internal/branches/disable/disable.go
@@ -2,22 +2,23 @@ package disable
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 func Run(ctx context.Context, fsys afero.Fs) error {
-	ref, err := utils.LoadProjectRef(fsys)
+	ref, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
 	resp, err := utils.GetSupabase().DisableBranchWithResponse(ctx, ref)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to disable preview branching: %w", err)
 	}
 	if resp.StatusCode() != http.StatusOK {
 		return errors.New("Unexpected error disabling preview branching: " + string(resp.Body))
diff --git a/internal/branches/get/get.go b/internal/branches/get/get.go
index ecfbf5be..5c245310 100644
--- a/internal/branches/get/get.go
+++ b/internal/branches/get/get.go
@@ -2,9 +2,9 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -12,7 +12,7 @@ import (
 func Run(ctx context.Context, branchId string) error {
 	resp, err := utils.GetSupabase().GetBranchDetailsWithResponse(ctx, branchId)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to retrieve preview branch: %w", err)
 	}
 	if resp.JSON200 == nil {
 		return errors.New("Unexpected error retrieving preview branch: " + string(resp.Body))
diff --git a/internal/branches/list/list.go b/internal/branches/list/list.go
index 17451e54..ef9a712a 100644
--- a/internal/branches/list/list.go
+++ b/internal/branches/list/list.go
@@ -2,23 +2,24 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 func Run(ctx context.Context, fsys afero.Fs) error {
-	ref, err := utils.LoadProjectRef(fsys)
+	ref, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
 	resp, err := utils.GetSupabase().GetBranchesWithResponse(ctx, ref)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list preview branches: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/branches/update/update.go b/internal/branches/update/update.go
index 63e0861a..e661c48f 100644
--- a/internal/branches/update/update.go
+++ b/internal/branches/update/update.go
@@ -2,9 +2,9 @@ package update
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -13,7 +13,7 @@ import (
 func Run(ctx context.Context, branchId string, body api.UpdateBranchBody, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().UpdateBranchWithResponse(ctx, branchId, body)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to update preview branch: %w", err)
 	}
 	if resp.JSON200 == nil {
 		return errors.New("Unexpected error updating preview branch: " + string(resp.Body))
diff --git a/internal/db/branch/create/create.go b/internal/db/branch/create/create.go
index fafbf1a9..98996e8c 100644
--- a/internal/db/branch/create/create.go
+++ b/internal/db/branch/create/create.go
@@ -4,7 +4,6 @@ import (
 	"bytes"
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -12,6 +11,7 @@ import (
 
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/pkg/stdcopy"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
diff --git a/internal/db/branch/delete/delete.go b/internal/db/branch/delete/delete.go
index 78456ddc..a3bfde6f 100644
--- a/internal/db/branch/delete/delete.go
+++ b/internal/db/branch/delete/delete.go
@@ -3,13 +3,13 @@ package delete
 import (
 	"bytes"
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"path/filepath"
 
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/pkg/stdcopy"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -51,7 +51,7 @@ func deleteBranchDir(branch string, fsys afero.Fs) error {
 	}
 
 	if err := fsys.RemoveAll(branchPath); err != nil {
-		return fmt.Errorf("Failed deleting branch %s: %w", utils.Aqua(branch), err)
+		return errors.Errorf("Failed deleting branch %s: %w", utils.Aqua(branch), err)
 	}
 
 	return nil
diff --git a/internal/db/branch/list/list.go b/internal/db/branch/list/list.go
index 72a8e50b..b1037ac1 100644
--- a/internal/db/branch/list/list.go
+++ b/internal/db/branch/list/list.go
@@ -1,12 +1,12 @@
 package list
 
 import (
-	"errors"
 	"fmt"
 	"io"
 	"os"
 	"path/filepath"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
diff --git a/internal/db/branch/switch_/switch_.go b/internal/db/branch/switch_/switch_.go
index 111cf394..462b26c6 100644
--- a/internal/db/branch/switch_/switch_.go
+++ b/internal/db/branch/switch_/switch_.go
@@ -2,11 +2,11 @@ package switch_
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"path/filepath"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
diff --git a/internal/db/diff/diff.go b/internal/db/diff/diff.go
index 31b2f520..28150183 100644
--- a/internal/db/diff/diff.go
+++ b/internal/db/diff/diff.go
@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/db/start"
@@ -22,7 +23,7 @@ func SaveDiff(out, file string, fsys afero.Fs) error {
 	} else if len(file) > 0 {
 		path := new.GetMigrationPath(utils.GetCurrentTimestamp(), file)
 		if err := afero.WriteFile(fsys, path, []byte(out), 0644); err != nil {
-			return err
+			return errors.Errorf("failed to save diff: %w", err)
 		}
 		fmt.Fprintln(os.Stderr, warnDiff)
 	} else {
@@ -63,7 +64,7 @@ func run(p utils.Program, ctx context.Context, schema []string, config pgconn.Co
 	}
 	defer utils.DockerRemove(shadow)
 	if !start.WaitForHealthyService(ctx, shadow, start.HealthTimeout) {
-		return start.ErrDatabase
+		return errors.New(start.ErrDatabase)
 	}
 	if err := MigrateShadowDatabase(ctx, shadow, fsys); err != nil {
 		return err
diff --git a/internal/db/diff/migra.go b/internal/db/diff/migra.go
index c497acfa..f429f631 100644
--- a/internal/db/diff/migra.go
+++ b/internal/db/diff/migra.go
@@ -4,7 +4,6 @@ import (
 	"bytes"
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -15,6 +14,7 @@ import (
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/go-connections/nat"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -151,7 +151,7 @@ func DiffSchemaMigra(ctx context.Context, source, target string, schema []string
 		&out,
 		&stderr,
 	); err != nil {
-		return "", fmt.Errorf("error diffing schema: %w:\n%s", err, stderr.String())
+		return "", errors.Errorf("error diffing schema: %w:\n%s", err, stderr.String())
 	}
 	return out.String(), nil
 }
@@ -164,7 +164,7 @@ func DiffDatabase(ctx context.Context, schema []string, config pgconn.Config, w
 	}
 	defer utils.DockerRemove(shadow)
 	if !start.WaitForHealthyService(ctx, shadow, start.HealthTimeout) {
-		return "", start.ErrDatabase
+		return "", errors.New(start.ErrDatabase)
 	}
 	if err := MigrateShadowDatabase(ctx, shadow, fsys, options...); err != nil {
 		return "", err
diff --git a/internal/db/dump/dump.go b/internal/db/dump/dump.go
index 62234ffe..c365edca 100644
--- a/internal/db/dump/dump.go
+++ b/internal/db/dump/dump.go
@@ -10,6 +10,7 @@ import (
 
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
@@ -30,7 +31,7 @@ func Run(ctx context.Context, path string, config pgconn.Config, schema []string
 	if len(path) > 0 {
 		f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to open dump file: %w", err)
 		}
 		defer f.Close()
 		outStream = f
diff --git a/internal/db/lint/lint.go b/internal/db/lint/lint.go
index 8f169570..22519ae5 100644
--- a/internal/db/lint/lint.go
+++ b/internal/db/lint/lint.go
@@ -9,6 +9,7 @@ import (
 	"os"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -80,13 +81,16 @@ func printResultJSON(result []Result, minLevel LintLevel, stdout io.Writer) erro
 	// Pretty print output
 	enc := json.NewEncoder(stdout)
 	enc.SetIndent("", "  ")
-	return enc.Encode(filtered)
+	if err := enc.Encode(filtered); err != nil {
+		return errors.Errorf("failed to print result json: %w", err)
+	}
+	return nil
 }
 
 func LintDatabase(ctx context.Context, conn *pgx.Conn, schema []string) ([]Result, error) {
 	tx, err := conn.Begin(ctx)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to begin transaction: %w", err)
 	}
 	if len(schema) == 0 {
 		schema, err = diff.LoadUserSchemas(ctx, conn, utils.InternalSchemas...)
@@ -101,7 +105,7 @@ func LintDatabase(ctx context.Context, conn *pgx.Conn, schema []string) ([]Resul
 		}
 	}()
 	if _, err := conn.Exec(ctx, ENABLE_PGSQL_CHECK); err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to enable pgsql_check: %w", err)
 	}
 	// Batch prepares statements
 	batch := pgx.Batch{}
@@ -115,18 +119,18 @@ func LintDatabase(ctx context.Context, conn *pgx.Conn, schema []string) ([]Resul
 		fmt.Fprintln(os.Stderr, "Linting schema:", s)
 		rows, err := br.Query()
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to query rows: %w", err)
 		}
 		// Parse result row
 		for rows.Next() {
 			var name string
 			var data []byte
 			if err := rows.Scan(&name, &data); err != nil {
-				return nil, err
+				return nil, errors.Errorf("failed to scan rows: %w", err)
 			}
 			var r Result
 			if err := json.Unmarshal(data, &r); err != nil {
-				return nil, err
+				return nil, errors.Errorf("failed to marshal json: %w", err)
 			}
 			// Update function name
 			r.Function = s + "." + name
@@ -134,7 +138,7 @@ func LintDatabase(ctx context.Context, conn *pgx.Conn, schema []string) ([]Resul
 		}
 		err = rows.Err()
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to parse rows: %w", err)
 		}
 	}
 	return result, nil
diff --git a/internal/db/pull/pull.go b/internal/db/pull/pull.go
index 9285c5a2..7fe9472a 100644
--- a/internal/db/pull/pull.go
+++ b/internal/db/pull/pull.go
@@ -3,10 +3,10 @@ package pull
 import (
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgerrcode"
 	"github.com/jackc/pgx/v4"
@@ -20,10 +20,15 @@ import (
 )
 
 var (
-	errConflict = errors.New("The remote database's migration history is not in sync with the contents of " + utils.Bold(utils.MigrationsDir) + `. Resolve this by:
-- Updating the project from version control to get the latest ` + utils.Bold(utils.MigrationsDir) + `,
-- Pushing unapplied migrations with ` + utils.Aqua("supabase db push") + `,
-- Or failing that, manually editing supabase_migrations.schema_migrations table with ` + utils.Aqua("supabase migration repair") + ".")
+	errConflict = errors.Errorf(`The remote database's migration history is not in sync with the contents of %s. Resolve this by:
+- Updating the project from version control to get the latest %s,
+- Pushing unapplied migrations with %s,
+- Or failing that, manually editing supabase_migrations.schema_migrations table with %s.`,
+		utils.Bold(utils.MigrationsDir),
+		utils.Bold(utils.MigrationsDir),
+		utils.Aqua("supabase db push"),
+		utils.Aqua("supabase migration repair"),
+	)
 	errMissing = errors.New("no migrations found")
 	errInSync  = errors.New("no schema changes found")
 )
@@ -61,7 +66,7 @@ func Run(ctx context.Context, schema []string, config pgconn.Config, name string
 func run(p utils.Program, ctx context.Context, schema []string, path string, conn *pgx.Conn, fsys afero.Fs) error {
 	config := conn.Config().Config
 	// 1. Assert `supabase/migrations` and `schema_migrations` are in sync.
-	if err := assertRemoteInSync(ctx, conn, fsys); err == errMissing {
+	if err := assertRemoteInSync(ctx, conn, fsys); errors.Is(err, errMissing) {
 		return dumpRemoteSchema(p, ctx, path, config, fsys)
 	} else if err != nil {
 		return err
@@ -82,7 +87,7 @@ func dumpRemoteSchema(p utils.Program, ctx context.Context, path string, config
 	p.Send(utils.StatusMsg("Dumping schema from remote database..."))
 	f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to open dump file: %w", err)
 	}
 	defer f.Close()
 	return dump.DumpSchema(ctx, config, nil, false, false, f)
@@ -96,9 +101,12 @@ func diffRemoteSchema(p utils.Program, ctx context.Context, schema []string, pat
 		return err
 	}
 	if len(output) == 0 {
-		return errInSync
+		return errors.New(errInSync)
+	}
+	if err := afero.WriteFile(fsys, path, []byte(output), 0644); err != nil {
+		return errors.Errorf("failed to write dump file: %w", err)
 	}
-	return afero.WriteFile(fsys, path, []byte(output), 0644)
+	return nil
 }
 
 func assertRemoteInSync(ctx context.Context, conn *pgx.Conn, fsys afero.Fs) error {
@@ -115,18 +123,18 @@ func assertRemoteInSync(ctx context.Context, conn *pgx.Conn, fsys afero.Fs) erro
 	}
 
 	if len(remoteMigrations) != len(localMigrations) {
-		return errConflict
+		return errors.New(errConflict)
 	}
 	for i, remoteTimestamp := range remoteMigrations {
 		// LoadLocalMigrations guarantees we always have a match
 		localTimestamp := utils.MigrateFilePattern.FindStringSubmatch(localMigrations[i])[1]
 		if localTimestamp != remoteTimestamp {
-			return errConflict
+			return errors.New(errConflict)
 		}
 	}
 
 	if len(localMigrations) == 0 {
-		return errMissing
+		return errors.New(errMissing)
 	}
 	return nil
 }
diff --git a/internal/db/push/push.go b/internal/db/push/push.go
index 4bd2ef14..a640e907 100644
--- a/internal/db/push/push.go
+++ b/internal/db/push/push.go
@@ -2,11 +2,11 @@ package push
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -63,7 +63,7 @@ func CreateCustomRoles(ctx context.Context, conn *pgx.Conn, w io.Writer, fsys af
 	if errors.Is(err, os.ErrNotExist) {
 		return nil
 	} else if err != nil {
-		return err
+		return errors.Errorf("failed to load custom roles: %w", err)
 	}
 	fmt.Fprintln(w, "Creating custom roles "+utils.Bold(utils.CustomRolesPath)+"...")
 	return apply.BatchExecDDL(ctx, conn, roles)
diff --git a/internal/db/reset/reset.go b/internal/db/reset/reset.go
index 9aa80784..d772abf1 100644
--- a/internal/db/reset/reset.go
+++ b/internal/db/reset/reset.go
@@ -3,7 +3,6 @@ package reset
 import (
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -16,6 +15,7 @@ import (
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/docker/errdefs"
 	"github.com/docker/docker/pkg/stdcopy"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgerrcode"
 	"github.com/jackc/pgx/v4"
@@ -26,6 +26,7 @@ import (
 	"github.com/supabase/cli/internal/migration/repair"
 	"github.com/supabase/cli/internal/status"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/pgxv5"
 )
 
 const (
@@ -43,7 +44,7 @@ var (
 func Run(ctx context.Context, version string, config pgconn.Config, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
 	if len(version) > 0 {
 		if _, err := strconv.Atoi(version); err != nil {
-			return repair.ErrInvalidVersion
+			return errors.New(repair.ErrInvalidVersion)
 		}
 		if _, err := repair.GetMigrationFile(version, fsys); err != nil {
 			return err
@@ -51,7 +52,7 @@ func Run(ctx context.Context, version string, config pgconn.Config, fsys afero.F
 	}
 	if !utils.IsLoopback(config.Host) {
 		if shouldReset := utils.PromptYesNo("Confirm resetting the remote database?", true, os.Stdin); !shouldReset {
-			return context.Canceled
+			return errors.New(context.Canceled)
 		}
 		return resetRemote(ctx, version, config, fsys, options...)
 	}
@@ -116,10 +117,10 @@ func resetDatabase14(ctx context.Context, version string, fsys afero.Fs, options
 
 func resetDatabase15(ctx context.Context, version string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
 	if err := utils.Docker.ContainerRemove(ctx, utils.DbId, types.ContainerRemoveOptions{Force: true}); err != nil {
-		return err
+		return errors.Errorf("failed to remove container: %w", err)
 	}
 	if err := utils.Docker.VolumeRemove(ctx, utils.DbId, true); err != nil {
-		return err
+		return errors.Errorf("failed to remove volume: %w", err)
 	}
 	// Skip syslog if vector container is not started
 	if _, err := utils.Docker.ContainerInspect(ctx, utils.VectorId); err != nil {
@@ -139,7 +140,7 @@ func resetDatabase15(ctx context.Context, version string, fsys afero.Fs, options
 		return err
 	}
 	if !start.WaitForHealthyService(ctx, utils.DbId, start.HealthTimeout) {
-		return start.ErrDatabase
+		return errors.New(start.ErrDatabase)
 	}
 	conn, err := utils.ConnectLocalPostgres(ctx, pgconn.Config{}, options...)
 	if err != nil {
@@ -191,12 +192,14 @@ func DisconnectClients(ctx context.Context, conn *pgx.Conn) error {
 	if _, err := conn.Exec(ctx, disconn); err != nil {
 		var pgErr *pgconn.PgError
 		if errors.As(err, &pgErr) && pgErr.Code != pgerrcode.InvalidCatalogName {
-			return err
+			return errors.Errorf("failed to disconnect clients: %w", err)
 		}
 	}
 	term := fmt.Sprintf(utils.TerminateDbSqlFmt, "postgres")
-	_, err := conn.Exec(ctx, term)
-	return err
+	if _, err := conn.Exec(ctx, term); err != nil {
+		return errors.Errorf("failed to terminate backend: %w", err)
+	}
+	return nil
 }
 
 func RestartDatabase(ctx context.Context, w io.Writer) error {
@@ -204,10 +207,10 @@ func RestartDatabase(ctx context.Context, w io.Writer) error {
 	// Some extensions must be manually restarted after pg_terminate_backend
 	// Ref: https://github.com/citusdata/pg_cron/issues/99
 	if err := utils.Docker.ContainerRestart(ctx, utils.DbId, container.StopOptions{}); err != nil {
-		return err
+		return errors.Errorf("failed to restart container: %w", err)
 	}
 	if !start.WaitForHealthyService(ctx, utils.DbId, start.HealthTimeout) {
-		return start.ErrDatabase
+		return errors.New(start.ErrDatabase)
 	}
 	return restartServices(ctx)
 }
@@ -217,7 +220,7 @@ func restartServices(ctx context.Context) error {
 	services := []string{utils.StorageId, utils.GotrueId, utils.RealtimeId}
 	result := utils.WaitAll(services, func(id string) error {
 		if err := utils.Docker.ContainerRestart(ctx, id, container.StopOptions{}); err != nil && !errdefs.IsNotFound(err) {
-			return fmt.Errorf("Failed to restart %s: %w", id, err)
+			return errors.Errorf("Failed to restart %s: %w", id, err)
 		}
 		return nil
 	})
@@ -253,7 +256,7 @@ func WaitForServiceReady(ctx context.Context, started []string) error {
 			}
 			logs.Close()
 		}
-		return fmt.Errorf("%w: %v", ErrUnhealthy, started)
+		return errors.Errorf("%w: %v", ErrUnhealthy, started)
 	}
 	return nil
 }
@@ -287,19 +290,14 @@ func resetRemote(ctx context.Context, version string, config pgconn.Config, fsys
 
 func ListSchemas(ctx context.Context, conn *pgx.Conn, exclude ...string) ([]string, error) {
 	exclude = likeEscapeSchema(exclude)
+	if len(exclude) == 0 {
+		exclude = append(exclude, "")
+	}
 	rows, err := conn.Query(ctx, LIST_SCHEMAS, exclude)
 	if err != nil {
-		return nil, err
-	}
-	schemas := []string{}
-	for rows.Next() {
-		var name string
-		if err := rows.Scan(&name); err != nil {
-			return nil, err
-		}
-		schemas = append(schemas, name)
+		return nil, errors.Errorf("failed to list schemas: %w", err)
 	}
-	return schemas, rows.Err()
+	return pgxv5.CollectStrings(rows)
 }
 
 func likeEscapeSchema(schemas []string) (result []string) {
diff --git a/internal/db/start/start.go b/internal/db/start/start.go
index 3a09ba89..95cfa85e 100644
--- a/internal/db/start/start.go
+++ b/internal/db/start/start.go
@@ -3,11 +3,9 @@ package start
 import (
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"io"
 	"os"
-	"path/filepath"
 	"strconv"
 	"strings"
 	"time"
@@ -16,6 +14,7 @@ import (
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/docker/client"
 	"github.com/docker/go-connections/nat"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -137,7 +136,7 @@ func StartDatabase(ctx context.Context, fsys afero.Fs, w io.Writer, options ...f
 		return err
 	}
 	if !WaitForHealthyService(ctx, utils.DbId, HealthTimeout) {
-		return ErrDatabase
+		return errors.New(ErrDatabase)
 	}
 	// Initialize if we are on PG14 and there's no existing db volume
 	if noBackupVolume {
@@ -181,14 +180,12 @@ func WithSyslogConfig(hostConfig container.HostConfig) container.HostConfig {
 
 func initCurrentBranch(fsys afero.Fs) error {
 	// Create _current_branch file to avoid breaking db branch commands
-	if _, err := fsys.Stat(utils.CurrBranchPath); err == nil || !errors.Is(err, os.ErrNotExist) {
-		return err
-	}
-	branchDir := filepath.Dir(utils.CurrBranchPath)
-	if err := utils.MkdirIfNotExistFS(fsys, branchDir); err != nil {
-		return err
+	if _, err := fsys.Stat(utils.CurrBranchPath); err == nil {
+		return nil
+	} else if !errors.Is(err, os.ErrNotExist) {
+		return errors.Errorf("failed init current branch: %w", err)
 	}
-	return afero.WriteFile(fsys, utils.CurrBranchPath, []byte("main"), 0644)
+	return utils.WriteFile(utils.CurrBranchPath, []byte("main"), fsys)
 }
 
 func initSchema(ctx context.Context, conn *pgx.Conn, host string, w io.Writer) error {
diff --git a/internal/encryption/get/get.go b/internal/encryption/get/get.go
index 5525d93a..6aa1f059 100644
--- a/internal/encryption/get/get.go
+++ b/internal/encryption/get/get.go
@@ -2,16 +2,16 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
 func Run(ctx context.Context, projectRef string) error {
 	resp, err := utils.GetSupabase().GetPgsodiumConfigWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to retrieve pgsodium config: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/encryption/update/update.go b/internal/encryption/update/update.go
index 2ee99fc6..b86efde9 100644
--- a/internal/encryption/update/update.go
+++ b/internal/encryption/update/update.go
@@ -2,11 +2,11 @@ package update
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/credentials"
 	"github.com/supabase/cli/pkg/api"
@@ -19,7 +19,7 @@ func Run(ctx context.Context, projectRef string, stdin *os.File) error {
 		RootKey: strings.TrimSpace(input),
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to update pgsodium config: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/functions/delete/delete.go b/internal/functions/delete/delete.go
index bd9c782a..63b71059 100644
--- a/internal/functions/delete/delete.go
+++ b/internal/functions/delete/delete.go
@@ -2,10 +2,10 @@ package delete
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -21,7 +21,7 @@ func Run(ctx context.Context, slug string, projectRef string, fsys afero.Fs) err
 	// 2. Delete Function.
 	resp, err := utils.GetSupabase().DeleteFunctionWithResponse(ctx, projectRef, slug)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to delete function: %w", err)
 	}
 	switch resp.StatusCode() {
 	case http.StatusNotFound:
diff --git a/internal/functions/deploy/deploy.go b/internal/functions/deploy/deploy.go
index e92b8672..8b638660 100644
--- a/internal/functions/deploy/deploy.go
+++ b/internal/functions/deploy/deploy.go
@@ -3,7 +3,6 @@ package deploy
 import (
 	"bytes"
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"net/http"
@@ -15,6 +14,7 @@ import (
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/go-units"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/spf13/viper"
 	"github.com/supabase/cli/internal/db/start"
@@ -59,7 +59,7 @@ func getFunctionSlugs(fsys afero.Fs) ([]string, error) {
 	pattern := filepath.Join(utils.FunctionsDir, "*", "index.ts")
 	paths, err := afero.Glob(fsys, pattern)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to glob function slugs: %w", err)
 	}
 	var slugs []string
 	for _, path := range paths {
@@ -74,14 +74,13 @@ func getFunctionSlugs(fsys afero.Fs) ([]string, error) {
 func bundleFunction(ctx context.Context, slug, dockerEntrypointPath, importMapPath string, fsys afero.Fs) (*bytes.Buffer, error) {
 	cwd, err := os.Getwd()
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to get working directory: %w", err)
 	}
 
 	// create temp directory to store generated eszip
 	hostOutputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", slug))
-	err = fsys.MkdirAll(hostOutputDir, 0755)
-	if err != nil {
-		return nil, err
+	if err := fsys.MkdirAll(hostOutputDir, 0755); err != nil {
+		return nil, errors.Errorf("failed to mkdir: %w", err)
 	}
 	defer func() {
 		if err := fsys.RemoveAll(hostOutputDir); err != nil {
@@ -134,7 +133,7 @@ func bundleFunction(ctx context.Context, slug, dockerEntrypointPath, importMapPa
 
 	eszipBytes, err := fsys.Open(filepath.Join(hostOutputDir, "output.eszip"))
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to open eszip: %w", err)
 	}
 	defer eszipBytes.Close()
 
@@ -144,7 +143,7 @@ func bundleFunction(ctx context.Context, slug, dockerEntrypointPath, importMapPa
 
 	_, err = io.Copy(brw, eszipBytes)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to compress brotli: %w", err)
 	}
 
 	return compressedBuf, nil
@@ -153,7 +152,7 @@ func bundleFunction(ctx context.Context, slug, dockerEntrypointPath, importMapPa
 func deployFunction(ctx context.Context, projectRef, slug, entrypointUrl, importMapUrl string, verifyJWT bool, functionBody io.Reader) error {
 	resp, err := utils.GetSupabase().GetFunctionWithResponse(ctx, projectRef, slug)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to retrieve function: %w", err)
 	}
 
 	switch resp.StatusCode() {
@@ -166,7 +165,7 @@ func deployFunction(ctx context.Context, projectRef, slug, entrypointUrl, import
 			EntrypointPath: &entrypointUrl,
 		}, eszipContentType, functionBody)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to create function: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("Failed to create a new Function on the Supabase project: " + string(resp.Body))
@@ -178,7 +177,7 @@ func deployFunction(ctx context.Context, projectRef, slug, entrypointUrl, import
 			EntrypointPath: &entrypointUrl,
 		}, eszipContentType, functionBody)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to update function: %w", err)
 		}
 		if resp.JSON200 == nil {
 			return errors.New("Failed to update an existing Function's body on the Supabase project: " + string(resp.Body))
@@ -210,7 +209,7 @@ func deployOne(ctx context.Context, slug, projectRef, importMapPath string, noVe
 	if importMapPath == "" {
 		resolved, err = filepath.Abs(utils.FallbackImportMapPath)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to resolve absolute path: %w", err)
 		}
 	}
 	exists, _ := afero.Exists(fsys, resolved)
diff --git a/internal/functions/download/download.go b/internal/functions/download/download.go
index 4fd907db..4d6be9fd 100644
--- a/internal/functions/download/download.go
+++ b/internal/functions/download/download.go
@@ -3,7 +3,6 @@ package download
 import (
 	"bytes"
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"net/http"
@@ -14,6 +13,7 @@ import (
 
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/db/start"
 	"github.com/supabase/cli/internal/utils"
@@ -53,16 +53,16 @@ func RunLegacy(ctx context.Context, slug string, projectRef string, fsys afero.F
 func getFunctionMetadata(ctx context.Context, projectRef, slug string) (*api.FunctionSlugResponse, error) {
 	resp, err := utils.GetSupabase().GetFunctionWithResponse(ctx, projectRef, slug)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to get function metadata: %w", err)
 	}
 
 	switch resp.StatusCode() {
 	case http.StatusNotFound:
-		return nil, errors.New("Function " + utils.Aqua(slug) + " does not exist on the Supabase project.")
+		return nil, errors.Errorf("Function %s does not exist on the Supabase project.", utils.Aqua(slug))
 	case http.StatusOK:
 		break
 	default:
-		return nil, errors.New("Failed to download Function " + utils.Aqua(slug) + " on the Supabase project: " + string(resp.Body))
+		return nil, errors.Errorf("Failed to download Function %s on the Supabase project: %s", utils.Aqua(slug), string(resp.Body))
 	}
 
 	if resp.JSON200.EntrypointPath == nil {
@@ -88,7 +88,7 @@ func downloadFunction(ctx context.Context, projectRef, slug, extractScriptPath s
 
 	resp, err := utils.GetSupabase().GetFunctionBodyWithResponse(ctx, projectRef, slug)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get function body: %w", err)
 	}
 	if resp.StatusCode() != http.StatusOK {
 		return errors.New("Unexpected error downloading Function: " + string(resp.Body))
@@ -103,7 +103,7 @@ func downloadFunction(ctx context.Context, projectRef, slug, extractScriptPath s
 	cmd.Stdout = os.Stdout
 	cmd.Stderr = &errBuf
 	if err := cmd.Run(); err != nil {
-		return fmt.Errorf("Error downloading function: %w\n%v", err, errBuf.String())
+		return errors.Errorf("Error downloading function: %w\n%v", err, errBuf.String())
 	}
 	return nil
 }
@@ -140,7 +140,7 @@ func downloadOne(ctx context.Context, slug string, projectRef string, fsys afero
 	fmt.Println("Downloading " + utils.Bold(slug))
 	resp, err := utils.GetSupabase().GetFunctionBodyWithResponse(ctx, projectRef, slug)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to get function body: %w", err)
 	}
 	if resp.StatusCode() != http.StatusOK {
 		return "", errors.New("Unexpected error downloading Function: " + string(resp.Body))
@@ -149,19 +149,21 @@ func downloadOne(ctx context.Context, slug string, projectRef string, fsys afero
 	// Create temp file to store downloaded eszip
 	eszipFile, err := afero.TempFile(fsys, "", slug)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to create temporary file: %w", err)
 	}
 	defer eszipFile.Close()
 
 	body := bytes.NewReader(resp.Body)
-	_, err = io.Copy(eszipFile, body)
-	return eszipFile.Name(), err
+	if _, err = io.Copy(eszipFile, body); err != nil {
+		return "", errors.Errorf("failed to download file: %w", err)
+	}
+	return eszipFile.Name(), nil
 }
 
 func extractOne(ctx context.Context, hostEszipPath string) error {
 	hostFuncDirPath, err := filepath.Abs(utils.FunctionsDir)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to resolve absolute path: %w", err)
 	}
 
 	dockerEszipPath := path.Join(dockerEszipDir, filepath.Base(hostEszipPath))
diff --git a/internal/functions/list/list.go b/internal/functions/list/list.go
index 6bd388f1..32b16b6d 100644
--- a/internal/functions/list/list.go
+++ b/internal/functions/list/list.go
@@ -2,10 +2,10 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
@@ -14,7 +14,7 @@ import (
 func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().GetFunctionsWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list functions: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/functions/new/new.go b/internal/functions/new/new.go
index eb36f341..f9447cf9 100644
--- a/internal/functions/new/new.go
+++ b/internal/functions/new/new.go
@@ -3,12 +3,12 @@ package new
 import (
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"html/template"
 	"os"
 	"path/filepath"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -32,9 +32,6 @@ func Run(ctx context.Context, slug string, fsys afero.Fs) error {
 		if err := utils.ValidateFunctionSlug(slug); err != nil {
 			return err
 		}
-		if _, err := fsys.Stat(funcDir); !errors.Is(err, os.ErrNotExist) {
-			return errors.New("Function " + utils.Aqua(slug) + " already exists locally.")
-		}
 	}
 
 	// 2. Create new function.
@@ -43,9 +40,9 @@ func Run(ctx context.Context, slug string, fsys afero.Fs) error {
 			return err
 		}
 		path := filepath.Join(funcDir, "index.ts")
-		f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
+		f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to create function entrypoint: %w", err)
 		}
 		defer f.Close()
 		// Templatize index.ts by config.toml if available
@@ -59,7 +56,7 @@ func Run(ctx context.Context, slug string, fsys afero.Fs) error {
 			Token: utils.Config.Auth.AnonKey,
 		}
 		if err := indexTemplate.Execute(f, config); err != nil {
-			return err
+			return errors.Errorf("failed to initialise function entrypoint: %w", err)
 		}
 	}
 
diff --git a/internal/functions/serve/serve.go b/internal/functions/serve/serve.go
index e2054848..dc30ed76 100644
--- a/internal/functions/serve/serve.go
+++ b/internal/functions/serve/serve.go
@@ -4,7 +4,6 @@ import (
 	"context"
 	_ "embed"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -15,6 +14,7 @@ import (
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/go-connections/nat"
+	"github.com/go-errors/errors"
 	"github.com/joho/godotenv"
 	"github.com/spf13/afero"
 	"github.com/spf13/viper"
@@ -66,18 +66,18 @@ func ServeFunctions(ctx context.Context, envFilePath string, noVerifyJWT *bool,
 			envFilePath = utils.FallbackEnvFilePath
 		}
 	} else if _, err := fsys.Stat(envFilePath); err != nil {
-		return fmt.Errorf("Failed to read env file: %w", err)
+		return errors.Errorf("Failed to read env file: %w", err)
 	}
 	cwd, err := os.Getwd()
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get working directory: %w", err)
 	}
 	if importMapPath != "" {
 		if !filepath.IsAbs(importMapPath) {
 			importMapPath = filepath.Join(cwd, importMapPath)
 		}
 		if _, err := fsys.Stat(importMapPath); err != nil {
-			return fmt.Errorf("Failed to read import map: %w", err)
+			return errors.Errorf("Failed to read import map: %w", err)
 		}
 	}
 	// 2. Parse user defined env
@@ -114,7 +114,7 @@ func ServeFunctions(ctx context.Context, envFilePath string, noVerifyJWT *bool,
 
 	fallbackImportMapPath := filepath.Join(cwd, utils.FallbackImportMapPath)
 	if exists, err := afero.Exists(fsys, fallbackImportMapPath); err != nil {
-		return fmt.Errorf("Failed to read fallback import map: %w", err)
+		return errors.Errorf("Failed to read fallback import map: %w", err)
 	} else if !exists {
 		fallbackImportMapPath = utils.AbsTempImportMapPath(cwd, utils.ImportMapsDir)
 		if err := utils.WriteFile(fallbackImportMapPath, []byte(`{"imports":{}}`), fsys); err != nil {
@@ -184,16 +184,16 @@ func parseEnvFile(envFilePath string, fsys afero.Fs) ([]string, error) {
 	}
 	f, err := fsys.Open(envFilePath)
 	if err != nil {
-		return env, err
+		return env, errors.Errorf("failed to open env file: %w", err)
 	}
 	defer f.Close()
 	envMap, err := godotenv.Parse(f)
 	if err != nil {
-		return env, err
+		return env, errors.Errorf("failed to parse env file: %w", err)
 	}
 	for name, value := range envMap {
 		if strings.HasPrefix(name, "SUPABASE_") {
-			return env, errors.New("Invalid env name: " + name + ". Env names cannot start with SUPABASE_.")
+			return env, errors.Errorf("Invalid env name: %s. Env names cannot start with SUPABASE_.", name)
 		}
 		env = append(env, name+"="+value)
 	}
@@ -210,12 +210,12 @@ func populatePerFunctionConfigs(binds []string, importMapPath string, noVerifyJW
 
 	cwd, err := os.Getwd()
 	if err != nil {
-		return nil, "", err
+		return nil, "", errors.Errorf("failed to get working directory: %w", err)
 	}
 
 	functions, err := afero.ReadDir(fsys, utils.FunctionsDir)
 	if err != nil {
-		return nil, "", err
+		return nil, "", errors.Errorf("failed to read directory: %w", err)
 	}
 	for _, function := range functions {
 		if !function.IsDir() {
@@ -257,7 +257,7 @@ func populatePerFunctionConfigs(binds []string, importMapPath string, noVerifyJW
 
 	functionsConfigBytes, err := json.Marshal(functionsConfig)
 	if err != nil {
-		return nil, "", err
+		return nil, "", errors.Errorf("failed to marshal config json: %w", err)
 	}
 
 	return binds, string(functionsConfigBytes), nil
diff --git a/internal/gen/keys/keys.go b/internal/gen/keys/keys.go
index 79f33c1e..af230c21 100644
--- a/internal/gen/keys/keys.go
+++ b/internal/gen/keys/keys.go
@@ -4,12 +4,12 @@ import (
 	"context"
 	"crypto/sha256"
 	"encoding/hex"
-	"errors"
 	"fmt"
 	"os"
 	"strings"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/go-git/go-git/v5"
 	"github.com/golang-jwt/jwt/v5"
 	"github.com/spf13/afero"
@@ -60,7 +60,7 @@ func GenerateSecrets(ctx context.Context, projectRef, branch string, fsys afero.
 	// Load JWT secret from api
 	resp, err := utils.GetSupabase().GetPostgRESTConfigWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get postgrest config: %w", err)
 	}
 	if resp.JSON200 == nil {
 		return errors.New("Unexpected error retrieving JWT secret: " + string(resp.Body))
@@ -79,11 +79,14 @@ func GenerateSecrets(ctx context.Context, projectRef, branch string, fsys afero.
 	anonToken := NewJWTToken(projectRef, "anon", expiry)
 	utils.Config.Auth.AnonKey, err = anonToken.SignedString([]byte(utils.Config.Auth.JwtSecret))
 	if err != nil {
-		return err
+		return errors.Errorf("failed to sign anon key: %w", err)
 	}
 	serviceToken := NewJWTToken(projectRef, "service_role", expiry)
 	utils.Config.Auth.ServiceRoleKey, err = serviceToken.SignedString([]byte(utils.Config.Auth.JwtSecret))
-	return err
+	if err != nil {
+		return errors.Errorf("failed to sign service_role key: %w", err)
+	}
+	return nil
 }
 
 func GetGitBranch(fsys afero.Fs) string {
diff --git a/internal/gen/types/typescript/typescript.go b/internal/gen/types/typescript/typescript.go
index 9eb1b55e..81d95f81 100644
--- a/internal/gen/types/typescript/typescript.go
+++ b/internal/gen/types/typescript/typescript.go
@@ -2,7 +2,6 @@ package typescript
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/url"
 	"os"
@@ -10,9 +9,11 @@ import (
 
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 	"github.com/supabase/cli/pkg/api"
 )
 
@@ -35,7 +36,7 @@ func Run(ctx context.Context, useLocal bool, useLinked bool, projectId string, d
 			IncludedSchemas: &included,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to get typescript types: %w", err)
 		}
 
 		if resp.JSON200 == nil {
@@ -114,7 +115,7 @@ func Run(ctx context.Context, useLocal bool, useLinked bool, projectId string, d
 	}
 
 	if useLinked {
-		projectId, err := utils.LoadProjectRef(fsys)
+		projectId, err := flags.LoadProjectRef(fsys)
 		if err != nil {
 			return err
 		}
@@ -124,7 +125,7 @@ func Run(ctx context.Context, useLocal bool, useLinked bool, projectId string, d
 			IncludedSchemas: &included,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to get typescript types: %w", err)
 		}
 
 		if resp.JSON200 == nil {
diff --git a/internal/hostnames/activate/activate.go b/internal/hostnames/activate/activate.go
index 40d4acc7..30814247 100644
--- a/internal/hostnames/activate/activate.go
+++ b/internal/hostnames/activate/activate.go
@@ -2,9 +2,9 @@ package activate
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/hostnames"
 	"github.com/supabase/cli/internal/utils"
@@ -27,7 +27,7 @@ func Run(ctx context.Context, projectRef string, includeRawOutput bool, fsys afe
 	{
 		resp, err := utils.GetSupabase().ActivateWithResponse(ctx, projectRef)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to active custom hostname: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to activate custom hostname config: " + string(resp.Body))
diff --git a/internal/hostnames/common.go b/internal/hostnames/common.go
index 8c7d0552..6756bc79 100644
--- a/internal/hostnames/common.go
+++ b/internal/hostnames/common.go
@@ -3,10 +3,10 @@ package hostnames
 import (
 	"context"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
 )
@@ -14,7 +14,7 @@ import (
 func GetCustomHostnameConfig(ctx context.Context, projectRef string) (*api.GetCustomHostnameConfigResponse, error) {
 	resp, err := utils.GetSupabase().GetCustomHostnameConfigWithResponse(ctx, projectRef)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to get custom hostname: %w", err)
 	}
 	if resp.JSON200 == nil {
 		return nil, errors.New("failed to get custom hostname config; received: " + string(resp.Body))
@@ -26,10 +26,10 @@ func VerifyCNAME(ctx context.Context, projectRef string, customHostname string)
 	expectedEndpoint := fmt.Sprintf("%s.", utils.GetSupabaseHost(projectRef))
 	cname, err := utils.ResolveCNAME(ctx, customHostname)
 	if err != nil {
-		return fmt.Errorf("expected custom hostname '%s' to have a CNAME record pointing to your project at '%s', but it failed to resolve: %w", customHostname, expectedEndpoint, err)
+		return errors.Errorf("expected custom hostname '%s' to have a CNAME record pointing to your project at '%s', but it failed to resolve: %w", customHostname, expectedEndpoint, err)
 	}
 	if cname != expectedEndpoint {
-		return fmt.Errorf("expected custom hostname '%s' to have a CNAME record pointing to your project at '%s', but it is currently set to '%s'", customHostname, expectedEndpoint, cname)
+		return errors.Errorf("expected custom hostname '%s' to have a CNAME record pointing to your project at '%s', but it is currently set to '%s'", customHostname, expectedEndpoint, cname)
 	}
 	return nil
 }
@@ -59,7 +59,7 @@ type RawResponse struct {
 func serializeRawOutput(response *api.UpdateCustomHostnameResponse) (string, error) {
 	output, err := json.MarshalIndent(response, "", "    ")
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to serialize json: %w", err)
 	}
 	return string(output), nil
 }
@@ -83,11 +83,11 @@ func TranslateStatus(response *api.UpdateCustomHostnameResponse, includeRawOutpu
 		var res RawResponse
 		rawBody, err := json.Marshal(response.Data)
 		if err != nil {
-			return "", fmt.Errorf("failed to serialize body: %w", err)
+			return "", errors.Errorf("failed to serialize body: %w", err)
 		}
 		err = json.Unmarshal(rawBody, &res)
 		if err != nil {
-			return "", fmt.Errorf("failed to deserialize body: %w", err)
+			return "", errors.Errorf("failed to deserialize body: %w", err)
 		}
 		return appendRawOutputIfNeeded(fmt.Sprintf(`Custom hostname configuration complete, and ready for activation.
 
@@ -98,11 +98,11 @@ Please ensure that your custom domain is set up as a CNAME record to your Supaba
 		var res RawResponse
 		rawBody, err := json.Marshal(response.Data)
 		if err != nil {
-			return "", fmt.Errorf("failed to serialize body: %w", err)
+			return "", errors.Errorf("failed to serialize body: %w", err)
 		}
 		err = json.Unmarshal(rawBody, &res)
 		if err != nil {
-			return "", fmt.Errorf("failed to deserialize body: %w", err)
+			return "", errors.Errorf("failed to deserialize body: %w", err)
 		}
 		owner := res.Result.OwnershipVerification
 		ssl := res.Result.Ssl.ValidationRecords
@@ -121,7 +121,7 @@ Please ensure that your custom domain is set up as a CNAME record to your Supaba
 			return appendRawOutputIfNeeded(fmt.Sprintf("SSL validation errors: \n\t- %s\n", valErrors), response, includeRawOutput), nil
 		}
 		if len(ssl) != 1 {
-			return "", fmt.Errorf("expected a single SSL verification record, received: %+v", ssl)
+			return "", errors.Errorf("expected a single SSL verification record, received: %+v", ssl)
 		}
 		records := ""
 		if owner.Name != "" {
diff --git a/internal/hostnames/create/create.go b/internal/hostnames/create/create.go
index 08a4b1e5..0bdc77a9 100644
--- a/internal/hostnames/create/create.go
+++ b/internal/hostnames/create/create.go
@@ -2,10 +2,10 @@ package create
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/hostnames"
 	"github.com/supabase/cli/internal/utils"
@@ -32,7 +32,7 @@ func Run(ctx context.Context, projectRef string, customHostname string, includeR
 			CustomHostname: hostname,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to create custom hostname: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to create custom hostname config: " + string(resp.Body))
diff --git a/internal/hostnames/delete/delete.go b/internal/hostnames/delete/delete.go
index bf2dd7c0..ad7b3de2 100644
--- a/internal/hostnames/delete/delete.go
+++ b/internal/hostnames/delete/delete.go
@@ -2,9 +2,9 @@ package delete
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -15,7 +15,7 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		resp, err := utils.GetSupabase().RemoveCustomHostnameConfigWithResponse(ctx, projectRef)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to delete custom hostname: %w", err)
 		}
 		if resp.StatusCode() != 200 {
 			return errors.New("failed to delete custom hostname config; received: " + resp.Status())
diff --git a/internal/hostnames/reverify/reverify.go b/internal/hostnames/reverify/reverify.go
index 63e96e28..05720bc9 100644
--- a/internal/hostnames/reverify/reverify.go
+++ b/internal/hostnames/reverify/reverify.go
@@ -2,9 +2,9 @@ package reverify
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/hostnames"
 	"github.com/supabase/cli/internal/utils"
@@ -16,7 +16,7 @@ func Run(ctx context.Context, projectRef string, includeRawOutput bool, fsys afe
 	{
 		resp, err := utils.GetSupabase().ReverifyWithResponse(ctx, projectRef)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to re-verify custom hostname: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to re-verify custom hostname config: " + string(resp.Body))
diff --git a/internal/init/init.go b/internal/init/init.go
index 41b1143b..f2b2e0a5 100644
--- a/internal/init/init.go
+++ b/internal/init/init.go
@@ -3,12 +3,12 @@ package init
 import (
 	_ "embed"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"io"
 	"os"
 	"path/filepath"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -25,16 +25,16 @@ var (
 	//go:embed templates/.vscode/settings.json
 	vscodeSettings string
 
-	errAlreadyInitialized = errors.New("Project already initialized. Remove " + utils.Bold(utils.ConfigPath) + " to reinitialize.")
+	errAlreadyInitialized = errors.Errorf("Project already initialized. Remove %s to reinitialize.", utils.Bold(utils.ConfigPath))
 )
 
 func Run(fsys afero.Fs, createVscodeSettings *bool, useOrioleDB bool) error {
 	// Sanity checks.
 	{
 		if _, err := fsys.Stat(utils.ConfigPath); err == nil {
-			return errAlreadyInitialized
+			return errors.New(errAlreadyInitialized)
 		} else if !errors.Is(err, os.ErrNotExist) {
-			return err
+			return errors.Errorf("failed to read config file: %w", err)
 		}
 	}
 
@@ -45,7 +45,7 @@ func Run(fsys afero.Fs, createVscodeSettings *bool, useOrioleDB bool) error {
 
 	// 2. Create `seed.sql`.
 	if _, err := fsys.Create(utils.SeedDataPath); err != nil {
-		return err
+		return errors.Errorf("failed to create seed file: %w", err)
 	}
 
 	// 3. Append to `.gitignore`.
@@ -78,17 +78,17 @@ func updateGitIgnore(ignorePath string, fsys afero.Fs) error {
 		// Add a line break when appending
 		contents = append(contents, '\n')
 	} else if !errors.Is(err, os.ErrNotExist) {
-		return err
+		return errors.Errorf("failed to read git ignore file: %w", err)
 	}
 
 	f, err := fsys.OpenFile(ignorePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create git ignore file: %w", err)
 	}
 	defer f.Close()
 
 	if _, err := f.Write(append(contents, initGitignore...)); err != nil {
-		return err
+		return errors.Errorf("failed to write git ignore file: %w", err)
 	}
 
 	return nil
@@ -100,14 +100,14 @@ func loadUserSettings(path string, fsys afero.Fs) (VSCodeSettings, error) {
 	// Open our jsonFile
 	jsonFile, err := fsys.Open(path)
 	if err != nil {
-		return nil, fmt.Errorf("failed to load %s: %w", utils.Bold(path), err)
+		return nil, errors.Errorf("failed to load settings file: %w", err)
 	}
 	defer jsonFile.Close()
 	// Parse and unmarshal JSON file.
 	var userSettings VSCodeSettings
 	dec := json.NewDecoder(jsonFile)
 	if err := dec.Decode(&userSettings); err != nil {
-		return nil, fmt.Errorf("failed to parse %s: %w", utils.Bold(path), err)
+		return nil, errors.Errorf("failed to parse settings: %w", err)
 	}
 	return userSettings, nil
 }
@@ -116,14 +116,14 @@ func saveUserSettings(path string, settings VSCodeSettings, fsys afero.Fs) error
 	// Open our jsonFile
 	jsonFile, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 	if err != nil {
-		return fmt.Errorf("failed to open %s: %w", utils.Bold(path), err)
+		return errors.Errorf("failed to create settings file: %w", err)
 	}
 	defer jsonFile.Close()
 	// Marshal JSON to file.
 	enc := json.NewEncoder(jsonFile)
 	enc.SetIndent("", "  ")
 	if err := enc.Encode(settings); err != nil {
-		return fmt.Errorf("failed to save %s: %w", utils.Bold(path), err)
+		return errors.Errorf("failed to save settings: %w", err)
 	}
 	return nil
 }
@@ -137,7 +137,7 @@ func updateJsonFile(path string, template string, fsys afero.Fs) error {
 	}
 	// Merge template into user settings.
 	if err := json.Unmarshal([]byte(template), &userSettings); err != nil {
-		return fmt.Errorf("failed to copy template: %w", err)
+		return errors.Errorf("failed to copy template: %w", err)
 	}
 	return saveUserSettings(path, userSettings, fsys)
 }
diff --git a/internal/inspect/bloat/bloat.go b/internal/inspect/bloat/bloat.go
index 3310e70a..d8040863 100644
--- a/internal/inspect/bloat/bloat.go
+++ b/internal/inspect/bloat/bloat.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -89,7 +90,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/blocking/blocking.go b/internal/inspect/blocking/blocking.go
index 817e97b7..3d418bf6 100644
--- a/internal/inspect/blocking/blocking.go
+++ b/internal/inspect/blocking/blocking.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"regexp"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -48,7 +49,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/cache/cache.go b/internal/inspect/cache/cache.go
index 0674bfab..88f3c65a 100644
--- a/internal/inspect/cache/cache.go
+++ b/internal/inspect/cache/cache.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -37,7 +38,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/calls/calls.go b/internal/inspect/calls/calls.go
index 8d79555d..faf289ee 100644
--- a/internal/inspect/calls/calls.go
+++ b/internal/inspect/calls/calls.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"regexp"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -40,7 +41,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/index_sizes/index_sizes.go b/internal/inspect/index_sizes/index_sizes.go
index b916ff68..2d5848bc 100644
--- a/internal/inspect/index_sizes/index_sizes.go
+++ b/internal/inspect/index_sizes/index_sizes.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -35,7 +36,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/index_usage/index_usage.go b/internal/inspect/index_usage/index_usage.go
index 6060a654..cd304609 100644
--- a/internal/inspect/index_usage/index_usage.go
+++ b/internal/inspect/index_usage/index_usage.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -44,7 +45,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/locks/locks.go b/internal/inspect/locks/locks.go
index ef8cafb2..0d3eb5cd 100644
--- a/internal/inspect/locks/locks.go
+++ b/internal/inspect/locks/locks.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"regexp"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -44,7 +45,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/long_running_queries/long_running_queries.go b/internal/inspect/long_running_queries/long_running_queries.go
index 72272fcb..9b18f527 100644
--- a/internal/inspect/long_running_queries/long_running_queries.go
+++ b/internal/inspect/long_running_queries/long_running_queries.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -39,7 +40,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/outliers/outliers.go b/internal/inspect/outliers/outliers.go
index f5421e28..33307045 100644
--- a/internal/inspect/outliers/outliers.go
+++ b/internal/inspect/outliers/outliers.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"regexp"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -40,7 +41,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/replication_slots/replication_slots.go b/internal/inspect/replication_slots/replication_slots.go
index d5d5a3da..97408d6c 100644
--- a/internal/inspect/replication_slots/replication_slots.go
+++ b/internal/inspect/replication_slots/replication_slots.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -41,7 +42,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/role_connections/role_connections.go b/internal/inspect/role_connections/role_connections.go
index 290b9f24..0f5c92e8 100644
--- a/internal/inspect/role_connections/role_connections.go
+++ b/internal/inspect/role_connections/role_connections.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -43,7 +44,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
@@ -57,9 +58,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 		sum += r.Active_connections
 	}
 
-	err = list.RenderTable(table)
-	if err != nil {
-		fmt.Println(err)
+	if err := list.RenderTable(table); err != nil {
 		return err
 	}
 
@@ -67,13 +66,10 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 		fmt.Printf("\nActive connections %d/%d\n\n", sum, result[0].Connection_limit)
 	}
 
-	ref, err := utils.LoadProjectRef(fsys)
-	if err != nil {
-		return err
+	if matches := utils.ProjectHostPattern.FindStringSubmatch(config.Host); len(matches) == 4 {
+		fmt.Println("Go to the dashboard for more here:")
+		fmt.Printf("https://app.supabase.com/project/%s/database/roles\n", matches[2])
 	}
 
-	fmt.Println("Go to the dashboard for more here:")
-	fmt.Printf("https://app.supabase.com/project/%s/database/roles\n", ref)
-
 	return nil
 }
diff --git a/internal/inspect/seq_scans/seq_scans.go b/internal/inspect/seq_scans/seq_scans.go
index 6e361a83..e0235118 100644
--- a/internal/inspect/seq_scans/seq_scans.go
+++ b/internal/inspect/seq_scans/seq_scans.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -31,7 +32,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/table_index_sizes/table_index_sizes.go b/internal/inspect/table_index_sizes/table_index_sizes.go
index c22cb117..62905833 100644
--- a/internal/inspect/table_index_sizes/table_index_sizes.go
+++ b/internal/inspect/table_index_sizes/table_index_sizes.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -34,7 +35,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/table_record_counts/table_record_counts.go b/internal/inspect/table_record_counts/table_record_counts.go
index 116a5234..ba204c84 100644
--- a/internal/inspect/table_record_counts/table_record_counts.go
+++ b/internal/inspect/table_record_counts/table_record_counts.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -33,7 +34,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/table_sizes/table_sizes.go b/internal/inspect/table_sizes/table_sizes.go
index a15f3464..579ba172 100644
--- a/internal/inspect/table_sizes/table_sizes.go
+++ b/internal/inspect/table_sizes/table_sizes.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -34,7 +35,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/total_index_size/total_index_size.go b/internal/inspect/total_index_size/total_index_size.go
index 8e6bf65e..38900177 100644
--- a/internal/inspect/total_index_size/total_index_size.go
+++ b/internal/inspect/total_index_size/total_index_size.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -32,7 +33,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/total_table_sizes/total_table_sizes.go b/internal/inspect/total_table_sizes/total_table_sizes.go
index e87092fb..e47f90b6 100644
--- a/internal/inspect/total_table_sizes/total_table_sizes.go
+++ b/internal/inspect/total_table_sizes/total_table_sizes.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -35,7 +36,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/unused_indexes/unused_indexes.go b/internal/inspect/unused_indexes/unused_indexes.go
index f6c77ef9..18fc06dc 100644
--- a/internal/inspect/unused_indexes/unused_indexes.go
+++ b/internal/inspect/unused_indexes/unused_indexes.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -38,7 +39,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/inspect/vacuum_stats/vacuum_stats.go b/internal/inspect/vacuum_stats/vacuum_stats.go
index db660603..220990ed 100644
--- a/internal/inspect/vacuum_stats/vacuum_stats.go
+++ b/internal/inspect/vacuum_stats/vacuum_stats.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -77,7 +78,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu
 	}
 	rows, err := conn.Query(ctx, QUERY)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to query rows: %w", err)
 	}
 	result, err := pgxv5.CollectRows[Result](rows)
 	if err != nil {
diff --git a/internal/link/link.go b/internal/link/link.go
index 3d0a5840..650515ba 100644
--- a/internal/link/link.go
+++ b/internal/link/link.go
@@ -5,18 +5,17 @@ import (
 	"fmt"
 	"io"
 	"os"
-	"path/filepath"
 	"strconv"
 	"strings"
 	"sync"
 
 	"github.com/BurntSushi/toml"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
 	"github.com/spf13/viper"
 	"github.com/supabase/cli/internal/migration/repair"
-	"github.com/supabase/cli/internal/services"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/credentials"
 	"github.com/supabase/cli/internal/utils/tenant"
@@ -68,10 +67,7 @@ func Run(ctx context.Context, projectRef, password string, fsys afero.Fs, option
 	}
 
 	// 3. Save project ref
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(utils.ProjectRefPath)); err != nil {
-		return err
-	}
-	return afero.WriteFile(fsys, utils.ProjectRefPath, []byte(projectRef), 0644)
+	return utils.WriteFile(utils.ProjectRefPath, []byte(projectRef), fsys)
 }
 
 func PostRun(projectRef string, stdout io.Writer, fsys afero.Fs) error {
@@ -82,7 +78,10 @@ func PostRun(projectRef string, stdout io.Writer, fsys afero.Fs) error {
 	fmt.Fprintln(os.Stderr, "Local config differs from linked project. Try updating", utils.Bold(utils.ConfigPath))
 	enc := toml.NewEncoder(stdout)
 	enc.Indent = ""
-	return enc.Encode(updatedConfig)
+	if err := enc.Encode(updatedConfig); err != nil {
+		return errors.Errorf("failed to marshal toml config: %w", err)
+	}
+	return nil
 }
 
 func linkServices(ctx context.Context, projectRef string, fsys afero.Fs) {
@@ -131,10 +130,10 @@ func linkServices(ctx context.Context, projectRef string, fsys afero.Fs) {
 func linkPostgrest(ctx context.Context, projectRef string) error {
 	resp, err := utils.GetSupabase().GetPostgRESTConfigWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get postgrest config: %w", err)
 	}
 	if resp.JSON200 == nil {
-		return fmt.Errorf("%w: %s", tenant.ErrAuthToken, string(resp.Body))
+		return errors.Errorf("%w: %s", tenant.ErrAuthToken, string(resp.Body))
 	}
 	updateApiConfig(*resp.JSON200)
 	return nil
@@ -145,10 +144,7 @@ func linkPostgrestVersion(ctx context.Context, projectRef string, fsys afero.Fs)
 	if err != nil {
 		return err
 	}
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(utils.RestVersionPath)); err != nil {
-		return err
-	}
-	return afero.WriteFile(fsys, utils.RestVersionPath, []byte(version), 0644)
+	return utils.WriteFile(utils.RestVersionPath, []byte(version), fsys)
 }
 
 func updateApiConfig(config api.PostgrestConfigWithJWTSecretResponse) {
@@ -181,10 +177,7 @@ func linkGotrueVersion(ctx context.Context, projectRef string, fsys afero.Fs) er
 	if err != nil {
 		return err
 	}
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(utils.GotrueVersionPath)); err != nil {
-		return err
-	}
-	return afero.WriteFile(fsys, utils.GotrueVersionPath, []byte(version), 0644)
+	return utils.WriteFile(utils.GotrueVersionPath, []byte(version), fsys)
 }
 
 func linkStorageVersion(ctx context.Context, projectRef string, fsys afero.Fs) error {
@@ -192,10 +185,7 @@ func linkStorageVersion(ctx context.Context, projectRef string, fsys afero.Fs) e
 	if err != nil {
 		return err
 	}
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(utils.StorageVersionPath)); err != nil {
-		return err
-	}
-	return afero.WriteFile(fsys, utils.StorageVersionPath, []byte(version), 0644)
+	return utils.WriteFile(utils.StorageVersionPath, []byte(version), fsys)
 }
 
 func linkDatabase(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) error {
@@ -210,14 +200,11 @@ func linkDatabase(ctx context.Context, config pgconn.Config, options ...func(*pg
 }
 
 func linkDatabaseVersion(ctx context.Context, projectRef string, fsys afero.Fs) error {
-	version, err := services.GetDatabaseVersion(ctx, projectRef)
+	version, err := tenant.GetDatabaseVersion(ctx, projectRef)
 	if err != nil {
 		return err
 	}
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(utils.PostgresVersionPath)); err != nil {
-		return err
-	}
-	return afero.WriteFile(fsys, utils.PostgresVersionPath, []byte(version), 0644)
+	return utils.WriteFile(utils.PostgresVersionPath, []byte(version), fsys)
 }
 
 func updatePostgresConfig(conn *pgx.Conn) {
@@ -239,10 +226,10 @@ func updatePostgresConfig(conn *pgx.Conn) {
 func linkPooler(ctx context.Context, projectRef string) error {
 	resp, err := utils.GetSupabase().V1GetPgbouncerConfigWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get pooler config: %w", err)
 	}
 	if resp.JSON200 == nil {
-		return fmt.Errorf("%w: %s", tenant.ErrAuthToken, string(resp.Body))
+		return errors.Errorf("%w: %s", tenant.ErrAuthToken, string(resp.Body))
 	}
 	updatePoolerConfig(*resp.JSON200)
 	return nil
diff --git a/internal/login/login.go b/internal/login/login.go
index a40ed1e0..15bd4cb7 100644
--- a/internal/login/login.go
+++ b/internal/login/login.go
@@ -16,6 +16,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/credentials"
@@ -58,7 +59,7 @@ func NewLoginEncryption() (LoginEncryption, error) {
 	enc := LoginEncryption{}
 	err := enc.generateKeys()
 	if err != nil {
-		return enc, fmt.Errorf("cannot generate crypto keys: %w", err)
+		return enc, errors.Errorf("cannot generate crypto keys: %w", err)
 	}
 	return enc, nil
 }
@@ -67,7 +68,7 @@ func (enc *LoginEncryption) generateKeys() error {
 	enc.curve = ecdh.P256()
 	privateKey, err := enc.curve.GenerateKey(rand.Reader)
 	if err != nil {
-		return fmt.Errorf("cannot generate encryption key: %w", err)
+		return errors.Errorf("cannot generate encryption key: %w", err)
 	}
 	enc.privateKey = privateKey
 	enc.publicKey = privateKey.PublicKey()
@@ -81,42 +82,42 @@ func (enc LoginEncryption) encodedPublicKey() string {
 func (enc LoginEncryption) decryptAccessToken(accessToken string, publicKey string, nonce string) (string, error) {
 	decodedAccessToken, err := hex.DecodeString(accessToken)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	decodedNonce, err := hex.DecodeString(nonce)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	decodedPublicKey, err := hex.DecodeString(publicKey)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	remotePublicKey, err := enc.curve.NewPublicKey(decodedPublicKey)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	secret, err := enc.privateKey.ECDH(remotePublicKey)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	block, err := aes.NewCipher(secret)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	aesgcm, err := cipher.NewGCM(block)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	decryptedAccessToken, err := aesgcm.Open(nil, decodedNonce, decodedAccessToken, nil)
 	if err != nil {
-		return "", fmt.Errorf("%s: %w", decryptionErrorMsg, err)
+		return "", errors.Errorf("%s: %w", decryptionErrorMsg, err)
 	}
 
 	return string(decryptedAccessToken), nil
@@ -128,11 +129,11 @@ func pollForAccessToken(ctx context.Context, url string) (AccessTokenResponse, e
 	// TODO: Move to OpenAPI-generated http client once we reach v1 on API schema.
 	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
 	if err != nil {
-		return accessTokenResponse, fmt.Errorf("cannot fetch access token: %w", err)
+		return accessTokenResponse, errors.Errorf("cannot fetch access token: %w", err)
 	}
 	resp, err := http.DefaultClient.Do(req)
 	if err != nil {
-		return accessTokenResponse, fmt.Errorf("cannot fetch access token: %w", err)
+		return accessTokenResponse, errors.Errorf("cannot fetch access token: %w", err)
 	}
 	defer resp.Body.Close()
 
@@ -154,24 +155,24 @@ func pollForAccessToken(ctx context.Context, url string) (AccessTokenResponse, e
 		body, err := io.ReadAll(resp.Body)
 
 		if err != nil {
-			return accessTokenResponse, fmt.Errorf("cannot read access token response body: %w", err)
+			return accessTokenResponse, errors.Errorf("cannot read access token response body: %w", err)
 		}
 
 		if err := json.Unmarshal(body, &accessTokenResponse); err != nil {
-			return accessTokenResponse, fmt.Errorf("cannot unmarshal access token response: %w", err)
+			return accessTokenResponse, errors.Errorf("cannot unmarshal access token response: %w", err)
 		}
 
 		return accessTokenResponse, nil
 	}
 
-	return accessTokenResponse, fmt.Errorf("HTTP %s: cannot retrieve access token", resp.Status)
+	return accessTokenResponse, errors.Errorf("HTTP %s: cannot retrieve access token", resp.Status)
 }
 
 func Run(ctx context.Context, stdout *os.File, params RunParams) error {
 	if params.Token != "" {
 		err := utils.SaveAccessToken(params.Token, params.Fsys)
 		if err != nil {
-			return fmt.Errorf("cannot save provided token: %w", err)
+			return errors.Errorf("cannot save provided token: %w", err)
 		}
 		fmt.Println(loggedInMsg)
 		return nil
@@ -193,7 +194,7 @@ func Run(ctx context.Context, stdout *os.File, params RunParams) error {
 		fmt.Fprintf(stdout, "Here is your login link in case browser did not open %s\n\n", utils.Bold(createLoginSessionUrl))
 
 		if err := RunOpenCmd(ctx, createLoginSessionUrl); err != nil {
-			return fmt.Errorf("cannot open default browser: %w", err)
+			return errors.Errorf("cannot open default browser: %w", err)
 		}
 	} else {
 		fmt.Fprintf(stdout, "Here is your login link, open it in the browser %s\n\n", utils.Bold(createLoginSessionUrl))
diff --git a/internal/migration/list/list.go b/internal/migration/list/list.go
index 0db6ffb4..bbd283ae 100644
--- a/internal/migration/list/list.go
+++ b/internal/migration/list/list.go
@@ -2,7 +2,6 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"math"
 	"os"
@@ -11,11 +10,13 @@ import (
 	"time"
 
 	"github.com/charmbracelet/glamour"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgerrcode"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/pgxv5"
 )
 
 const LIST_MIGRATION_VERSION = "SELECT version FROM supabase_migrations.schema_migrations ORDER BY version"
@@ -52,17 +53,9 @@ func LoadRemoteMigrations(ctx context.Context, conn *pgx.Conn) ([]string, error)
 			// If migration history table is undefined, the remote project has no migrations
 			return nil, nil
 		}
-		return nil, err
-	}
-	versions := []string{}
-	for rows.Next() {
-		var version string
-		if err := rows.Scan(&version); err != nil {
-			return nil, err
-		}
-		versions = append(versions, version)
+		return nil, errors.Errorf("failed to query rows: %w", err)
 	}
-	return versions, nil
+	return pgxv5.CollectStrings(rows)
 }
 
 const (
@@ -118,11 +111,11 @@ func RenderTable(markdown string) error {
 		glamour.WithWordWrap(-1),
 	)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to initialise terminal renderer: %w", err)
 	}
 	out, err := r.Render(markdown)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to render markdown: %w", err)
 	}
 	fmt.Print(out)
 	return nil
@@ -152,7 +145,7 @@ func LoadPartialMigrations(version string, fsys afero.Fs) ([]string, error) {
 	}
 	localMigrations, err := afero.ReadDir(fsys, utils.MigrationsDir)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to read directory: %w", err)
 	}
 	var names []string
 	for i, migration := range localMigrations {
diff --git a/internal/migration/new/new.go b/internal/migration/new/new.go
index 9c93cfe8..b9437cd5 100644
--- a/internal/migration/new/new.go
+++ b/internal/migration/new/new.go
@@ -6,6 +6,7 @@ import (
 	"os"
 	"path/filepath"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -17,16 +18,16 @@ func Run(migrationName string, stdin afero.File, fsys afero.Fs) error {
 	}
 	f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to open migration file: %w", err)
 	}
 	defer f.Close()
 
 	if fi, err := stdin.Stat(); err != nil {
-		return err
+		return errors.Errorf("failed to initialise stdin: %w", err)
 	} else if (fi.Mode() & os.ModeCharDevice) == 0 {
 		// Ref: https://stackoverflow.com/a/26567513
 		if _, err := io.Copy(f, stdin); err != nil {
-			return err
+			return errors.Errorf("failed to copy from stdin: %w", err)
 		}
 	}
 
diff --git a/internal/migration/repair/repair.go b/internal/migration/repair/repair.go
index 59a35274..e57e4da4 100644
--- a/internal/migration/repair/repair.go
+++ b/internal/migration/repair/repair.go
@@ -2,13 +2,13 @@ package repair
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"os"
 	"path/filepath"
 	"strconv"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgtype"
 	"github.com/jackc/pgx/v4"
@@ -36,7 +36,7 @@ var ErrInvalidVersion = errors.New("invalid version number")
 
 func Run(ctx context.Context, config pgconn.Config, version, status string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
 	if _, err := strconv.Atoi(version); err != nil {
-		return ErrInvalidVersion
+		return errors.New(ErrInvalidVersion)
 	}
 	conn, err := utils.ConnectByConfig(ctx, config, options...)
 	if err != nil {
@@ -63,8 +63,10 @@ func UpdateMigrationTable(ctx context.Context, conn *pgx.Conn, version, status s
 	case Reverted:
 		DeleteVersionSQL(&batch, version)
 	}
-	_, err := conn.PgConn().ExecBatch(ctx, &batch).ReadAll()
-	return err
+	if _, err := conn.PgConn().ExecBatch(ctx, &batch).ReadAll(); err != nil {
+		return errors.Errorf("failed to update migration table: %w", err)
+	}
+	return nil
 }
 
 func batchCreateTable() pgconn.Batch {
@@ -79,8 +81,10 @@ func batchCreateTable() pgconn.Batch {
 
 func CreateMigrationTable(ctx context.Context, conn *pgx.Conn) error {
 	batch := batchCreateTable()
-	_, err := conn.PgConn().ExecBatch(ctx, &batch).ReadAll()
-	return err
+	if _, err := conn.PgConn().ExecBatch(ctx, &batch).ReadAll(); err != nil {
+		return errors.Errorf("failed to create migration table: %w", err)
+	}
+	return nil
 }
 
 func InsertVersionSQL(batch *pgconn.Batch, version, name string, stats []string) {
@@ -115,10 +119,10 @@ func GetMigrationFile(version string, fsys afero.Fs) (string, error) {
 	path := filepath.Join(utils.MigrationsDir, version+"_*.sql")
 	matches, err := afero.Glob(fsys, path)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to glob migration files: %w", err)
 	}
 	if len(matches) == 0 {
-		return "", fmt.Errorf("glob %s: %w", path, os.ErrNotExist)
+		return "", errors.Errorf("glob %s: %w", path, os.ErrNotExist)
 	}
 	return matches[0], nil
 }
@@ -140,7 +144,7 @@ func NewMigrationFromVersion(version string, fsys afero.Fs) (*MigrationFile, err
 func NewMigrationFromFile(path string, fsys afero.Fs) (*MigrationFile, error) {
 	sql, err := fsys.Open(path)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to open migration file: %w", err)
 	}
 	defer sql.Close()
 	// Unless explicitly specified, Use file length as max buffer size
@@ -190,7 +194,7 @@ func (m *MigrationFile) ExecBatch(ctx context.Context, conn *pgx.Conn) error {
 		if i < len(m.Lines) {
 			stat = m.Lines[i]
 		}
-		return fmt.Errorf("%w\nAt statement %d: %s", err, i, utils.Aqua(stat))
+		return errors.Errorf("%w\nAt statement %d: %s", err, i, stat)
 	}
 	return nil
 }
@@ -202,5 +206,8 @@ func (m *MigrationFile) ExecBatchWithCache(ctx context.Context, conn *pgx.Conn)
 		batch.Queue(line)
 	}
 	// No need to track version here because there are no schema changes
-	return conn.SendBatch(ctx, &batch).Close()
+	if err := conn.SendBatch(ctx, &batch).Close(); err != nil {
+		return errors.Errorf("failed to send batch: %w", err)
+	}
+	return nil
 }
diff --git a/internal/migration/squash/squash.go b/internal/migration/squash/squash.go
index 449b49c1..dd342268 100644
--- a/internal/migration/squash/squash.go
+++ b/internal/migration/squash/squash.go
@@ -2,12 +2,12 @@ package squash
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"path/filepath"
 	"strconv"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -23,7 +23,7 @@ var ErrMissingVersion = errors.New("version not found")
 func Run(ctx context.Context, version string, config pgconn.Config, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
 	if len(version) > 0 {
 		if _, err := strconv.Atoi(version); err != nil {
-			return repair.ErrInvalidVersion
+			return errors.New(repair.ErrInvalidVersion)
 		}
 		if _, err := repair.GetMigrationFile(version, fsys); err != nil {
 			return err
@@ -49,7 +49,7 @@ func squashToVersion(ctx context.Context, version string, fsys afero.Fs, options
 		return err
 	}
 	if len(migrations) == 0 {
-		return ErrMissingVersion
+		return errors.New(ErrMissingVersion)
 	}
 	// Migrate to target version and dump
 	path := filepath.Join(utils.MigrationsDir, migrations[len(migrations)-1])
@@ -86,7 +86,7 @@ func squashMigrations(ctx context.Context, migrations []string, fsys afero.Fs, o
 	path := filepath.Join(utils.MigrationsDir, migrations[len(migrations)-1])
 	f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to open migration file: %w", err)
 	}
 	defer f.Close()
 	config := pgconn.Config{
@@ -126,5 +126,8 @@ func baselineMigrations(ctx context.Context, config pgconn.Config, version strin
 	batch := pgx.Batch{}
 	batch.Queue(DELETE_MIGRATION_BEFORE, m.Version)
 	batch.Queue(repair.INSERT_MIGRATION_VERSION, m.Version, m.Name, m.Lines)
-	return conn.SendBatch(ctx, &batch).Close()
+	if err := conn.SendBatch(ctx, &batch).Close(); err != nil {
+		return errors.Errorf("failed to update migration history: %w", err)
+	}
+	return nil
 }
diff --git a/internal/orgs/create/create.go b/internal/orgs/create/create.go
index 7cddbc4e..a455e925 100644
--- a/internal/orgs/create/create.go
+++ b/internal/orgs/create/create.go
@@ -2,9 +2,9 @@ package create
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
 )
@@ -12,7 +12,7 @@ import (
 func Run(ctx context.Context, name string) error {
 	resp, err := utils.GetSupabase().CreateOrganizationWithResponse(ctx, api.CreateOrganizationJSONRequestBody{Name: name})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create organization: %w", err)
 	}
 
 	if resp.JSON201 == nil {
diff --git a/internal/orgs/list/list.go b/internal/orgs/list/list.go
index a1d308bc..d7216a24 100644
--- a/internal/orgs/list/list.go
+++ b/internal/orgs/list/list.go
@@ -2,10 +2,10 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -13,7 +13,7 @@ import (
 func Run(ctx context.Context) error {
 	resp, err := utils.GetSupabase().GetOrganizationsWithResponse(ctx)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list organizations: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/postgresConfig/get/get.go b/internal/postgresConfig/get/get.go
index 99ea70ec..1a6db221 100644
--- a/internal/postgresConfig/get/get.go
+++ b/internal/postgresConfig/get/get.go
@@ -7,8 +7,9 @@ import (
 	"io"
 	"strings"
 
-	"github.com/charmbracelet/glamour"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
+	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
 )
 
@@ -40,20 +41,9 @@ func PrintOutPostgresConfigOverrides(config map[string]interface{}) error {
 		))
 	}
 
-	r, err := glamour.NewTermRenderer(
-		glamour.WithAutoStyle(),
-		glamour.WithWordWrap(-1),
-	)
-	if err != nil {
-		return err
-	}
-
-	out, err := r.Render(strings.Join(markdownTable, ""))
-	if err != nil {
+	if err := list.RenderTable(strings.Join(markdownTable, "")); err != nil {
 		return err
 	}
-
-	fmt.Print(out)
 	fmt.Println("- End of Custom Postgres Config -")
 	return nil
 }
@@ -61,20 +51,20 @@ func PrintOutPostgresConfigOverrides(config map[string]interface{}) error {
 func GetCurrentPostgresConfig(ctx context.Context, projectRef string) (map[string]interface{}, error) {
 	resp, err := utils.GetSupabase().GetConfig(ctx, projectRef)
 	if err != nil {
-		return nil, fmt.Errorf("failed to retrieve Postgres config overrides: %w", err)
+		return nil, errors.Errorf("failed to retrieve Postgres config overrides: %w", err)
 	}
 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("error in retrieving Postgres config overrides: %s", resp.Status)
+		return nil, errors.Errorf("error in retrieving Postgres config overrides: %s", resp.Status)
 	}
 	contents, err := io.ReadAll(resp.Body)
 	if err != nil {
-		return nil, fmt.Errorf("failed to read response body: %w", err)
+		return nil, errors.Errorf("failed to read response body: %w", err)
 	}
 
 	var config map[string]interface{}
 	err = json.Unmarshal(contents, &config)
 	if err != nil {
-		return nil, fmt.Errorf("failed to unmarshal response body: %w. Contents were %s", err, contents)
+		return nil, errors.Errorf("failed to unmarshal response body: %w. Contents were %s", err, contents)
 	}
 	return config, nil
 }
diff --git a/internal/postgresConfig/update/update.go b/internal/postgresConfig/update/update.go
index 1a18c722..8b27cb69 100644
--- a/internal/postgresConfig/update/update.go
+++ b/internal/postgresConfig/update/update.go
@@ -4,10 +4,10 @@ import (
 	"bytes"
 	"context"
 	"encoding/json"
-	"fmt"
 	"strconv"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/postgresConfig/get"
 	"github.com/supabase/cli/internal/utils"
@@ -19,7 +19,7 @@ func Run(ctx context.Context, projectRef string, values []string, replaceOverrid
 	for _, config := range values {
 		splits := strings.Split(config, "=")
 		if len(splits) != 2 {
-			return fmt.Errorf("expected config value in key:value format, received: '%s'", config)
+			return errors.Errorf("expected config value in key:value format, received: '%s'", config)
 		}
 		newConfigOverrides[splits[0]] = splits[1]
 	}
@@ -51,17 +51,17 @@ func Run(ctx context.Context, projectRef string, values []string, replaceOverrid
 	{
 		bts, err := json.Marshal(finalOverrides)
 		if err != nil {
-			return fmt.Errorf("failed to serialize config overrides: %w", err)
+			return errors.Errorf("failed to serialize config overrides: %w", err)
 		}
 		resp, err := utils.GetSupabase().UpdateConfigWithBodyWithResponse(ctx, projectRef, "application/json", bytes.NewReader(bts))
 		if err != nil {
-			return err
+			return errors.Errorf("failed to update config overrides: %w", err)
 		}
 		if resp.JSON200 == nil {
 			if resp.StatusCode() == 400 {
-				return fmt.Errorf("failed to update config overrides: %s (%s). This usually indicates that an unsupported or invalid config override was attempted. Please refer to https://supabase.com/docs/guides/platform/custom-postgres-config", resp.Status(), string(resp.Body))
+				return errors.Errorf("failed to update config overrides: %s (%s). This usually indicates that an unsupported or invalid config override was attempted. Please refer to https://supabase.com/docs/guides/platform/custom-postgres-config", resp.Status(), string(resp.Body))
 			}
-			return fmt.Errorf("failed to update config overrides: %s (%s)", resp.Status(), string(resp.Body))
+			return errors.Errorf("failed to update config overrides: %s (%s)", resp.Status(), string(resp.Body))
 		}
 	}
 	return get.Run(ctx, projectRef, fsys)
diff --git a/internal/projects/apiKeys/api_keys.go b/internal/projects/apiKeys/api_keys.go
index be3a1fc6..3862cb41 100644
--- a/internal/projects/apiKeys/api_keys.go
+++ b/internal/projects/apiKeys/api_keys.go
@@ -2,10 +2,10 @@ package apiKeys
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
@@ -14,7 +14,7 @@ import (
 func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().GetProjectApiKeysWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get api keys: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/projects/create/create.go b/internal/projects/create/create.go
index 9e1f0c0b..ad9aa38e 100644
--- a/internal/projects/create/create.go
+++ b/internal/projects/create/create.go
@@ -2,9 +2,9 @@ package create
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -17,7 +17,7 @@ func Run(ctx context.Context, params api.CreateProjectBody, fsys afero.Fs) error
 
 	resp, err := utils.GetSupabase().CreateProjectWithResponse(ctx, params)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create project: %w", err)
 	}
 
 	if resp.JSON201 == nil {
diff --git a/internal/projects/delete/delete.go b/internal/projects/delete/delete.go
index 2a771b06..5ed36a3e 100644
--- a/internal/projects/delete/delete.go
+++ b/internal/projects/delete/delete.go
@@ -2,11 +2,11 @@ package delete
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/credentials"
@@ -26,7 +26,7 @@ func PreRun(ref string) error {
 func Run(ctx context.Context, ref string, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().DeleteProjectWithResponse(ctx, ref)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to delete project: %w", err)
 	}
 
 	switch resp.StatusCode() {
@@ -35,7 +35,7 @@ func Run(ctx context.Context, ref string, fsys afero.Fs) error {
 	case http.StatusOK:
 		break
 	default:
-		return errors.New("Failed to delete project " + utils.Aqua(ref) + ": " + string(resp.Body))
+		return errors.Errorf("Failed to delete project %s: %s", utils.Aqua(ref), string(resp.Body))
 	}
 
 	// Unlink project
diff --git a/internal/projects/list/list.go b/internal/projects/list/list.go
index 5e07c393..fe25cb97 100644
--- a/internal/projects/list/list.go
+++ b/internal/projects/list/list.go
@@ -2,28 +2,29 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"strings"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 func Run(ctx context.Context, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().GetProjectsWithResponse(ctx)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list projects: %w", err)
 	}
 
 	if resp.JSON200 == nil {
 		return errors.New("Unexpected error retrieving projects: " + string(resp.Body))
 	}
 
-	projectRef, err := utils.LoadProjectRef(fsys)
+	projectRef, err := flags.LoadProjectRef(fsys)
 	if err != nil && err != utils.ErrNotLinked {
 		fmt.Fprintln(os.Stderr, err)
 	}
diff --git a/internal/restrictions/get/get.go b/internal/restrictions/get/get.go
index 15462b04..d7b99afd 100644
--- a/internal/restrictions/get/get.go
+++ b/internal/restrictions/get/get.go
@@ -2,9 +2,9 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -15,15 +15,12 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		resp, err := utils.GetSupabase().GetNetworkRestrictionsWithResponse(ctx, projectRef)
 		if err != nil {
-			return fmt.Errorf("failed to retrieve network restrictions: %w", err)
+			return errors.Errorf("failed to retrieve network restrictions: %w", err)
 		}
 		if resp.JSON200 == nil {
 			return errors.New("failed to retrieve network restrictions; received: " + string(resp.Body))
 		}
 
-		if err != nil {
-			return err
-		}
 		fmt.Printf("DB Allowed CIDRs: %+v\n", resp.JSON200.Config.DbAllowedCidrs)
 		fmt.Printf("Restrictions applied successfully: %+v\n", resp.JSON200.Status == "applied")
 		return nil
diff --git a/internal/restrictions/update/update.go b/internal/restrictions/update/update.go
index 7eace20d..aa97f7c4 100644
--- a/internal/restrictions/update/update.go
+++ b/internal/restrictions/update/update.go
@@ -2,10 +2,10 @@ package update
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -15,13 +15,13 @@ func validateCidrs(cidrs []string, bypassChecks bool) error {
 	for _, cidr := range cidrs {
 		ip, _, err := net.ParseCIDR(cidr)
 		if err != nil {
-			return fmt.Errorf("failed to parse IP: %s", cidr)
+			return errors.Errorf("failed to parse IP: %s", cidr)
 		}
 		if ip.IsPrivate() && !bypassChecks {
-			return fmt.Errorf("private IP provided: %s", cidr)
+			return errors.Errorf("private IP provided: %s", cidr)
 		}
 		if ip.To4() == nil {
-			return fmt.Errorf("only IPv4 supported at the moment: %s", cidr)
+			return errors.Errorf("only IPv4 supported at the moment: %s", cidr)
 		}
 	}
 	return nil
@@ -42,7 +42,7 @@ func Run(ctx context.Context, projectRef string, dbCidrsToAllow []string, bypass
 			DbAllowedCidrs: dbCidrsToAllow,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to apply network restrictions: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to update network restrictions: " + string(resp.Body))
diff --git a/internal/secrets/list/list.go b/internal/secrets/list/list.go
index ef00023e..ecb94f07 100644
--- a/internal/secrets/list/list.go
+++ b/internal/secrets/list/list.go
@@ -2,10 +2,10 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
@@ -14,7 +14,7 @@ import (
 func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().GetSecretsWithResponse(ctx, projectRef)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list secrets: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/secrets/set/set.go b/internal/secrets/set/set.go
index d3d066f1..517de12d 100644
--- a/internal/secrets/set/set.go
+++ b/internal/secrets/set/set.go
@@ -2,11 +2,11 @@ package set
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/joho/godotenv"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
@@ -21,7 +21,7 @@ func Run(ctx context.Context, projectRef, envFilePath string, args []string, fsy
 		if envFilePath != "" {
 			envMap, err := godotenv.Read(envFilePath)
 			if err != nil {
-				return err
+				return errors.Errorf("failed to read env file: %w", err)
 			}
 			for name, value := range envMap {
 				secret := api.CreateSecretBody{
@@ -49,7 +49,7 @@ func Run(ctx context.Context, projectRef, envFilePath string, args []string, fsy
 
 		resp, err := utils.GetSupabase().CreateSecretsWithResponse(ctx, projectRef, secrets)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to set secrets: %w", err)
 		}
 
 		// TODO: remove the StatusOK case after 2022-08-20
diff --git a/internal/secrets/unset/unset.go b/internal/secrets/unset/unset.go
index 60ea7bc9..7be11587 100644
--- a/internal/secrets/unset/unset.go
+++ b/internal/secrets/unset/unset.go
@@ -2,10 +2,10 @@ package unset
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -16,7 +16,7 @@ func Run(ctx context.Context, projectRef string, args []string, fsys afero.Fs) e
 	{
 		resp, err := utils.GetSupabase().DeleteSecretsWithResponse(ctx, projectRef, args)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to delete secrets: %w", err)
 		}
 
 		if resp.StatusCode() != http.StatusOK {
diff --git a/internal/services/services.go b/internal/services/services.go
index 12b792a1..9c16aac4 100644
--- a/internal/services/services.go
+++ b/internal/services/services.go
@@ -2,7 +2,6 @@ package services
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 	"sync"
@@ -10,37 +9,23 @@ import (
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 	"github.com/supabase/cli/internal/utils/tenant"
 )
 
-var (
-	errDatabaseVersion = errors.New("Database version not found.")
-	suggestLinkCommand = fmt.Sprintf("Run %s to sync your local image versions with the linked project.", utils.Aqua("supabase link"))
-)
+var suggestLinkCommand = fmt.Sprintf("Run %s to sync your local image versions with the linked project.", utils.Aqua("supabase link"))
 
 func Run(ctx context.Context, fsys afero.Fs) error {
 	_ = utils.LoadConfigFS(fsys)
-	serviceImages := []string{
-		utils.Config.Db.Image,
-		utils.Config.Auth.Image,
-		utils.Config.Api.Image,
-		utils.RealtimeImage,
-		utils.Config.Storage.Image,
-		utils.EdgeRuntimeImage,
-		utils.StudioImage,
-		utils.PgmetaImage,
-		utils.LogflareImage,
-		utils.PgbouncerImage,
-		utils.ImageProxyImage,
-	}
+	serviceImages := GetServiceImages()
 
 	linked := make(map[string]string)
-	if projectRef, err := utils.LoadProjectRef(fsys); err == nil {
+	if projectRef, err := flags.LoadProjectRef(fsys); err == nil {
 		var wg sync.WaitGroup
 		wg.Add(4)
 		go func() {
 			defer wg.Done()
-			if version, err := GetDatabaseVersion(ctx, projectRef); err == nil {
+			if version, err := tenant.GetDatabaseVersion(ctx, projectRef); err == nil {
 				linked[utils.Config.Db.Image] = version
 			}
 		}()
@@ -82,18 +67,18 @@ func Run(ctx context.Context, fsys afero.Fs) error {
 	return list.RenderTable(table)
 }
 
-func GetDatabaseVersion(ctx context.Context, projectRef string) (string, error) {
-	resp, err := utils.GetSupabase().GetProjectsWithResponse(ctx)
-	if err != nil {
-		return "", err
-	}
-	if resp.JSON200 == nil {
-		return "", errors.New("Unexpected error retrieving projects: " + string(resp.Body))
-	}
-	for _, project := range *resp.JSON200 {
-		if project.Id == projectRef && len(project.Database.Version) > 0 {
-			return project.Database.Version, nil
-		}
+func GetServiceImages() []string {
+	return []string{
+		utils.Config.Db.Image,
+		utils.Config.Auth.Image,
+		utils.Config.Api.Image,
+		utils.RealtimeImage,
+		utils.Config.Storage.Image,
+		utils.EdgeRuntimeImage,
+		utils.StudioImage,
+		utils.PgmetaImage,
+		utils.LogflareImage,
+		utils.PgbouncerImage,
+		utils.ImageProxyImage,
 	}
-	return "", errDatabaseVersion
 }
diff --git a/internal/snippets/download/download.go b/internal/snippets/download/download.go
index 170ab76d..605115d6 100644
--- a/internal/snippets/download/download.go
+++ b/internal/snippets/download/download.go
@@ -2,9 +2,9 @@ package download
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -12,7 +12,7 @@ import (
 func Run(ctx context.Context, snippetId string, fsys afero.Fs) error {
 	resp, err := utils.GetSupabase().GetSnippetWithResponse(ctx, snippetId)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to download snippet: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/snippets/list/list.go b/internal/snippets/list/list.go
index df679d1e..921c7b2f 100644
--- a/internal/snippets/list/list.go
+++ b/internal/snippets/list/list.go
@@ -2,24 +2,25 @@ package list
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 	"github.com/supabase/cli/pkg/api"
 )
 
 func Run(ctx context.Context, fsys afero.Fs) error {
-	ref, err := utils.LoadProjectRef(fsys)
+	ref, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
 	resp, err := utils.GetSupabase().ListSnippetsWithResponse(ctx, &api.ListSnippetsParams{ProjectRef: &ref})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list snippets: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/ssl_enforcement/get/get.go b/internal/ssl_enforcement/get/get.go
index ff7d71b0..8a71c6c7 100644
--- a/internal/ssl_enforcement/get/get.go
+++ b/internal/ssl_enforcement/get/get.go
@@ -2,9 +2,9 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -15,15 +15,12 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		resp, err := utils.GetSupabase().GetSslEnforcementConfigWithResponse(ctx, projectRef)
 		if err != nil {
-			return fmt.Errorf("failed to retrieve SSL enforcement config: %w", err)
+			return errors.Errorf("failed to retrieve SSL enforcement config: %w", err)
 		}
 		if resp.JSON200 == nil {
 			return errors.New("failed to retrieve SSL enforcement config; received: " + string(resp.Body))
 		}
 
-		if err != nil {
-			return err
-		}
 		if resp.JSON200.CurrentConfig.Database && resp.JSON200.AppliedSuccessfully {
 			fmt.Println("SSL is being enforced.")
 		} else {
diff --git a/internal/ssl_enforcement/update/update.go b/internal/ssl_enforcement/update/update.go
index 36511175..4ad7e1d0 100644
--- a/internal/ssl_enforcement/update/update.go
+++ b/internal/ssl_enforcement/update/update.go
@@ -2,9 +2,9 @@ package update
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -20,7 +20,7 @@ func Run(ctx context.Context, projectRef string, enforceDbSsl bool, fsys afero.F
 			},
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to update ssl enforcement: %w", err)
 		}
 		if resp.JSON200 == nil {
 			return errors.New("failed to update SSL enforcement confnig: " + string(resp.Body))
diff --git a/internal/sso/create/create.go b/internal/sso/create/create.go
index 1c273142..cfaeedf1 100644
--- a/internal/sso/create/create.go
+++ b/internal/sso/create/create.go
@@ -2,13 +2,11 @@ package create
 
 import (
 	"context"
-	"errors"
-	"fmt"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
-
 	"github.com/supabase/cli/internal/sso/internal/render"
 	"github.com/supabase/cli/internal/sso/internal/saml"
 	"github.com/supabase/cli/internal/utils"
@@ -43,7 +41,7 @@ func Run(ctx context.Context, params RunParams) error {
 	} else if params.MetadataURL != "" {
 		if !params.SkipURLValidation {
 			if err := saml.ValidateMetadataURL(ctx, params.MetadataURL); err != nil {
-				return fmt.Errorf("%w Use --skip-url-validation to suppress this error", err)
+				return errors.Errorf("%w Use --skip-url-validation to suppress this error", err)
 			}
 		}
 
@@ -65,7 +63,7 @@ func Run(ctx context.Context, params RunParams) error {
 
 	resp, err := utils.GetSupabase().CreateProviderForProjectWithResponse(ctx, params.ProjectRef, body)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create sso provider: %w", err)
 	}
 
 	if resp.JSON201 == nil {
diff --git a/internal/sso/get/get.go b/internal/sso/get/get.go
index fadc5848..b1e27cc2 100644
--- a/internal/sso/get/get.go
+++ b/internal/sso/get/get.go
@@ -2,11 +2,11 @@ package get
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/sso/internal/render"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -20,7 +20,7 @@ func Run(ctx context.Context, ref, providerId, format string) error {
 
 	if resp.JSON200 == nil {
 		if resp.StatusCode() == http.StatusNotFound {
-			return fmt.Errorf("An identity provider with ID %q could not be found.", providerId)
+			return errors.Errorf("An identity provider with ID %q could not be found.", providerId)
 		}
 
 		return errors.New("Unexpected error fetching identity provider: " + string(resp.Body))
diff --git a/internal/sso/internal/render/render.go b/internal/sso/internal/render/render.go
index 98cecc6a..3f3a03db 100644
--- a/internal/sso/internal/render/render.go
+++ b/internal/sso/internal/render/render.go
@@ -5,8 +5,9 @@ import (
 	"fmt"
 	"strings"
 
-	"github.com/charmbracelet/glamour"
+	"github.com/go-errors/errors"
 	"github.com/go-xmlfmt/xmlfmt"
+	"github.com/supabase/cli/internal/migration/list"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
 )
@@ -32,7 +33,7 @@ func formatMetadataSource(provider api.Provider) string {
 func formatAttributeMapping(attributeMapping *api.AttributeMapping) (string, error) {
 	data, err := json.MarshalIndent(attributeMapping, "", "  ")
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to marshal attribute mapping: %w", err)
 	}
 
 	return string(data), nil
@@ -91,21 +92,7 @@ func ListMarkdown(providers []api.Provider) error {
 		))
 	}
 
-	r, err := glamour.NewTermRenderer(
-		glamour.WithAutoStyle(),
-		glamour.WithWordWrap(-1),
-	)
-	if err != nil {
-		return err
-	}
-
-	out, err := r.Render(strings.Join(markdownTable, ""))
-	if err != nil {
-		return err
-	}
-
-	fmt.Print(out)
-	return nil
+	return list.RenderTable(strings.Join(markdownTable, ""))
 }
 
 func SingleMarkdown(provider api.Provider) error {
@@ -165,21 +152,7 @@ func SingleMarkdown(provider api.Provider) error {
 		markdownTable = append(markdownTable, "", "## SAML 2.0 Metadata XML", "```xml", prettyXML, "```")
 	}
 
-	r, err := glamour.NewTermRenderer(
-		glamour.WithAutoStyle(),
-		glamour.WithWordWrap(-1),
-	)
-	if err != nil {
-		return err
-	}
-
-	out, err := r.Render(strings.Join(markdownTable, "\n"))
-	if err != nil {
-		return err
-	}
-
-	fmt.Print(out)
-	return nil
+	return list.RenderTable(strings.Join(markdownTable, "\n"))
 }
 
 func InfoMarkdown(ref string) error {
@@ -203,19 +176,5 @@ func InfoMarkdown(ref string) error {
 		fmt.Sprintf("https://%s.supabase.co", ref),
 	))
 
-	r, err := glamour.NewTermRenderer(
-		glamour.WithAutoStyle(),
-		glamour.WithWordWrap(-1),
-	)
-	if err != nil {
-		return err
-	}
-
-	out, err := r.Render(strings.Join(markdownTable, "\n"))
-	if err != nil {
-		return err
-	}
-
-	fmt.Print(out)
-	return nil
+	return list.RenderTable(strings.Join(markdownTable, "\n"))
 }
diff --git a/internal/sso/internal/saml/files.go b/internal/sso/internal/saml/files.go
index dd8a937a..0fe3648d 100644
--- a/internal/sso/internal/saml/files.go
+++ b/internal/sso/internal/saml/files.go
@@ -3,14 +3,13 @@ package saml
 import (
 	"context"
 	"encoding/json"
-	"errors"
-	"fmt"
 	"io"
 	"net/http"
 	"net/url"
 	"strings"
 	"unicode/utf8"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/pkg/api"
 )
@@ -20,12 +19,12 @@ var DefaultClient = http.DefaultClient
 func ReadMetadataFile(fsys afero.Fs, path string) (string, error) {
 	file, err := fsys.Open(path)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to open metadata file: %w", err)
 	}
 
 	data, err := io.ReadAll(file)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to read metadata file: %w", err)
 	}
 
 	if err := ValidateMetadata(data, path); err != nil {
@@ -38,18 +37,13 @@ func ReadMetadataFile(fsys afero.Fs, path string) (string, error) {
 func ReadAttributeMappingFile(fsys afero.Fs, path string) (*api.AttributeMapping, error) {
 	file, err := fsys.Open(path)
 	if err != nil {
-		return nil, err
-	}
-
-	data, err := io.ReadAll(file)
-	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to open attribute mapping: %w", err)
 	}
 
 	var mapping api.AttributeMapping
-
-	if err := json.Unmarshal(data, &mapping); err != nil {
-		return nil, err
+	dec := json.NewDecoder(file)
+	if err := dec.Decode(&mapping); err != nil {
+		return nil, errors.Errorf("failed to parse attribute mapping: %w", err)
 	}
 
 	return &mapping, nil
@@ -57,7 +51,7 @@ func ReadAttributeMappingFile(fsys afero.Fs, path string) (*api.AttributeMapping
 
 func ValidateMetadata(data []byte, source string) error {
 	if !utf8.Valid(data) {
-		return fmt.Errorf("SAML Metadata XML at %q is not UTF-8 encoded", source)
+		return errors.Errorf("SAML Metadata XML at %q is not UTF-8 encoded", source)
 	}
 
 	return nil
@@ -66,7 +60,7 @@ func ValidateMetadata(data []byte, source string) error {
 func ValidateMetadataURL(ctx context.Context, metadataURL string) error {
 	parsed, err := url.ParseRequestURI(metadataURL)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to parse metadata uri: %w", err)
 	}
 
 	if strings.ToLower(parsed.Scheme) != "https" {
@@ -75,29 +69,25 @@ func ValidateMetadataURL(ctx context.Context, metadataURL string) error {
 
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to initialise http request: %w", err)
 	}
 
 	req.Header.Add("Accept", "application/xml")
 
 	resp, err := DefaultClient.Do(req)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to send http request: %w", err)
 	}
 	defer resp.Body.Close()
 
 	if resp.StatusCode != http.StatusOK {
-		return fmt.Errorf("received HTTP %v when fetching metatada at %q", resp.Status, metadataURL)
+		return errors.Errorf("received HTTP %v when fetching metatada at %q", resp.Status, metadataURL)
 	}
 
 	data, err := io.ReadAll(resp.Body)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to read http response: %w", err)
 	}
 
-	if err := ValidateMetadata(data, metadataURL); err != nil {
-		return err
-	}
-
-	return nil
+	return ValidateMetadata(data, metadataURL)
 }
diff --git a/internal/sso/list/list.go b/internal/sso/list/list.go
index 02ad3fb8..82dcd42f 100644
--- a/internal/sso/list/list.go
+++ b/internal/sso/list/list.go
@@ -2,10 +2,10 @@ package list
 
 import (
 	"context"
-	"errors"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/sso/internal/render"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -13,7 +13,7 @@ import (
 func Run(ctx context.Context, ref, format string) error {
 	resp, err := utils.GetSupabase().ListAllProvidersWithResponse(ctx, ref)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list sso providers: %w", err)
 	}
 
 	if resp.JSON200 == nil {
diff --git a/internal/sso/remove/remove.go b/internal/sso/remove/remove.go
index 03fea14b..29518c59 100644
--- a/internal/sso/remove/remove.go
+++ b/internal/sso/remove/remove.go
@@ -2,11 +2,10 @@ package remove
 
 import (
 	"context"
-	"errors"
-	"fmt"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/sso/internal/render"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -15,12 +14,12 @@ import (
 func Run(ctx context.Context, ref, providerId, format string) error {
 	resp, err := utils.GetSupabase().RemoveProviderByIdWithResponse(ctx, ref, providerId)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to remove sso provider: %w", err)
 	}
 
 	if resp.JSON200 == nil {
 		if resp.StatusCode() == http.StatusNotFound {
-			return fmt.Errorf("An identity provider with ID %q could not be found.", providerId)
+			return errors.Errorf("An identity provider with ID %q could not be found.", providerId)
 		}
 
 		return errors.New("Unexpected error removing identity provider: " + string(resp.Body))
diff --git a/internal/sso/update/update.go b/internal/sso/update/update.go
index 41eb69fd..0f75e85e 100644
--- a/internal/sso/update/update.go
+++ b/internal/sso/update/update.go
@@ -2,13 +2,11 @@ package update
 
 import (
 	"context"
-	"errors"
-	"fmt"
 	"net/http"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
-
 	"github.com/supabase/cli/internal/sso/internal/render"
 	"github.com/supabase/cli/internal/sso/internal/saml"
 	"github.com/supabase/cli/internal/utils"
@@ -35,12 +33,12 @@ type RunParams struct {
 func Run(ctx context.Context, params RunParams) error {
 	getResp, err := utils.GetSupabase().GetProviderByIdWithResponse(ctx, params.ProjectRef, params.ProviderID)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to get sso provider: %w", err)
 	}
 
 	if getResp.JSON200 == nil {
 		if getResp.StatusCode() == http.StatusNotFound {
-			return fmt.Errorf("An identity provider with ID %q could not be found.", params.ProviderID)
+			return errors.Errorf("An identity provider with ID %q could not be found.", params.ProviderID)
 		}
 
 		return errors.New("unexpected error fetching identity provider: " + string(getResp.Body))
@@ -58,7 +56,7 @@ func Run(ctx context.Context, params RunParams) error {
 	} else if params.MetadataURL != "" {
 		if !params.SkipURLValidation {
 			if err := saml.ValidateMetadataURL(ctx, params.MetadataURL); err != nil {
-				return fmt.Errorf("%w Use --skip-url-validation to suppress this error.", err)
+				return errors.Errorf("%w Use --skip-url-validation to suppress this error.", err)
 			}
 		}
 
@@ -105,7 +103,7 @@ func Run(ctx context.Context, params RunParams) error {
 
 	putResp, err := utils.GetSupabase().UpdateProviderByIdWithResponse(ctx, params.ProjectRef, params.ProviderID, body)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to update sso provider: %w", err)
 	}
 
 	if putResp.JSON200 == nil {
diff --git a/internal/start/start.go b/internal/start/start.go
index 380a4bed..91bda92d 100644
--- a/internal/start/start.go
+++ b/internal/start/start.go
@@ -4,7 +4,6 @@ import (
 	"bytes"
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"os"
 	"path"
@@ -17,6 +16,7 @@ import (
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/api/types/network"
 	"github.com/docker/go-connections/nat"
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/afero"
@@ -142,7 +142,7 @@ func run(p utils.Program, ctx context.Context, fsys afero.Fs, excludedContainers
 			EdgeRuntimeId: utils.EdgeRuntimeId,
 			DbId:          utils.DbId,
 		}); err != nil {
-			return err
+			return errors.Errorf("failed to exec template: %w", err)
 		}
 		p.Send(utils.StatusMsg("Starting syslog driver..."))
 		if _, err := utils.DockerStart(
@@ -222,7 +222,7 @@ EOF
 		case utils.LogflareBigQuery:
 			workdir, err := os.Getwd()
 			if err != nil {
-				return err
+				return errors.Errorf("failed to get working directory: %w", err)
 			}
 			hostJwtPath := filepath.Join(workdir, utils.Config.Analytics.GcpJwtPath)
 			bind = append(bind, hostJwtPath+":/opt/app/rel/logflare/bin/gcloud.json")
@@ -296,7 +296,7 @@ EOF
 			LogflareId:    utils.LogflareId,
 			ApiPort:       utils.Config.Api.Port,
 		}); err != nil {
-			return err
+			return errors.Errorf("failed to exec template: %w", err)
 		}
 
 		binds := []string{}
@@ -309,7 +309,7 @@ EOF
 				var err error
 				hostPath, err = filepath.Abs(hostPath)
 				if err != nil {
-					return err
+					return errors.Errorf("failed to resolve absolute path: %w", err)
 				}
 			}
 			dockerPath := path.Join(nginxEmailTemplateDir, id+filepath.Ext(hostPath))
diff --git a/internal/status/status.go b/internal/status/status.go
index a7efc343..33271bb7 100644
--- a/internal/status/status.go
+++ b/internal/status/status.go
@@ -9,6 +9,7 @@ import (
 	"reflect"
 
 	"github.com/docker/docker/client"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -99,9 +100,9 @@ func AssertContainerHealthy(ctx context.Context, container string) error {
 	if resp, err := utils.Docker.ContainerInspect(ctx, container); err != nil {
 		return err
 	} else if !resp.State.Running {
-		return fmt.Errorf("%s container is not running: %s", container, resp.State.Status)
+		return errors.Errorf("%s container is not running: %s", container, resp.State.Status)
 	} else if resp.State.Health != nil && resp.State.Health.Status != "healthy" {
-		return fmt.Errorf("%s container is not ready: %s", container, resp.State.Health.Status)
+		return errors.Errorf("%s container is not ready: %s", container, resp.State.Health.Status)
 	}
 	return nil
 }
diff --git a/internal/stop/stop.go b/internal/stop/stop.go
index 9f5e4714..1bd6974c 100644
--- a/internal/stop/stop.go
+++ b/internal/stop/stop.go
@@ -3,7 +3,6 @@ package stop
 import (
 	"context"
 	_ "embed"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -11,6 +10,7 @@ import (
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/api/types/container"
 	"github.com/docker/docker/errdefs"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -43,7 +43,7 @@ func stop(ctx context.Context, backup bool, w io.Writer) error {
 		Filters: args,
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to list containers: %w", err)
 	}
 	// Gracefully shutdown containers
 	var ids []string
@@ -54,13 +54,16 @@ func stop(ctx context.Context, backup bool, w io.Writer) error {
 	}
 	fmt.Fprintln(w, "Stopping containers...")
 	result := utils.WaitAll(ids, func(id string) error {
-		return utils.Docker.ContainerStop(ctx, id, container.StopOptions{})
+		if err := utils.Docker.ContainerStop(ctx, id, container.StopOptions{}); err != nil {
+			return errors.Errorf("failed to stop container: %w", err)
+		}
+		return nil
 	})
 	if err := errors.Join(result...); err != nil {
 		return err
 	}
 	if _, err := utils.Docker.ContainersPrune(ctx, args); err != nil {
-		return err
+		return errors.Errorf("failed to prune containers: %w", err)
 	}
 	// Remove named volumes
 	if backup {
@@ -80,7 +83,7 @@ func stop(ctx context.Context, backup bool, w io.Writer) error {
 		}
 		result = utils.WaitAll(volumes, func(name string) error {
 			if err := utils.Docker.VolumeRemove(ctx, name, true); err != nil && !errdefs.IsNotFound(err) {
-				return fmt.Errorf("Failed to remove volume %s: %w", name, err)
+				return errors.Errorf("Failed to remove volume %s: %w", name, err)
 			}
 			return nil
 		})
@@ -89,6 +92,8 @@ func stop(ctx context.Context, backup bool, w io.Writer) error {
 		}
 	}
 	// Remove networks.
-	_, err = utils.Docker.NetworksPrune(ctx, args)
-	return err
+	if _, err = utils.Docker.NetworksPrune(ctx, args); err != nil {
+		return errors.Errorf("failed to prune networks: %w", err)
+	}
+	return nil
 }
diff --git a/internal/storage/client/objects.go b/internal/storage/client/objects.go
index 12ef1a3b..67f688c6 100644
--- a/internal/storage/client/objects.go
+++ b/internal/storage/client/objects.go
@@ -9,6 +9,7 @@ import (
 	"path"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/internal/utils/tenant"
@@ -65,19 +66,19 @@ func ListStorageObjects(ctx context.Context, projectRef, bucket, prefix string,
 func UploadStorageObject(ctx context.Context, projectRef, remotePath, localPath string, fsys afero.Fs) error {
 	f, err := fsys.Open(localPath)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to open file: %w", err)
 	}
 	defer f.Close()
 	// Decode mimetype
 	header := io.LimitReader(f, 512)
 	buf, err := io.ReadAll(header)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to read file: %w", err)
 	}
 	mimetype := http.DetectContentType(buf)
 	_, err = f.Seek(0, io.SeekStart)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to seek file: %w", err)
 	}
 	// Prepare request
 	apiKey, err := tenant.GetApiKeys(ctx, projectRef)
@@ -88,7 +89,7 @@ func UploadStorageObject(ctx context.Context, projectRef, remotePath, localPath
 	url := fmt.Sprintf("https://%s/storage/v1/object/%s", utils.GetSupabaseHost(projectRef), remotePath)
 	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, f)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to initialise http request: %w", err)
 	}
 	req.Header.Add("Authorization", "Bearer "+apiKey.ServiceRole)
 	req.Header.Add("Content-Type", mimetype)
@@ -97,15 +98,15 @@ func UploadStorageObject(ctx context.Context, projectRef, remotePath, localPath
 	// Sends request
 	resp, err := http.DefaultClient.Do(req)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to send http request: %w", err)
 	}
 	defer resp.Body.Close()
 	if resp.StatusCode != http.StatusOK {
 		body, err := io.ReadAll(resp.Body)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to read http response: %w", err)
 		}
-		return fmt.Errorf("Error status %d: %s", resp.StatusCode, body)
+		return errors.Errorf("Error status %d: %s", resp.StatusCode, body)
 	}
 	return nil
 }
@@ -119,30 +120,32 @@ func DownloadStorageObject(ctx context.Context, projectRef, remotePath, localPat
 	url := fmt.Sprintf("https://%s/storage/v1/object/%s", utils.GetSupabaseHost(projectRef), remotePath)
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to initialise http request: %w", err)
 	}
 	req.Header.Add("Authorization", "Bearer "+apiKey.ServiceRole)
 	// Sends request
 	resp, err := http.DefaultClient.Do(req)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to send http request: %w", err)
 	}
 	defer resp.Body.Close()
 	if resp.StatusCode != http.StatusOK {
 		body, err := io.ReadAll(resp.Body)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to read http response: %w", err)
 		}
-		return fmt.Errorf("Error status %d: %s", resp.StatusCode, body)
+		return errors.Errorf("Error status %d: %s", resp.StatusCode, body)
 	}
 	// Streams to file
 	f, err := fsys.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to open file: %w", err)
 	}
 	defer f.Close()
-	_, err = io.Copy(f, resp.Body)
-	return err
+	if _, err = io.Copy(f, resp.Body); err != nil {
+		return errors.Errorf("failed to write file: %w", err)
+	}
+	return nil
 }
 
 type MoveObjectRequest struct {
diff --git a/internal/storage/cp/cp.go b/internal/storage/cp/cp.go
index eaf972e9..72e7cfc8 100644
--- a/internal/storage/cp/cp.go
+++ b/internal/storage/cp/cp.go
@@ -2,7 +2,6 @@ package cp
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"io/fs"
 	"net/url"
@@ -11,11 +10,13 @@ import (
 	"path/filepath"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/storage"
 	"github.com/supabase/cli/internal/storage/client"
 	"github.com/supabase/cli/internal/storage/ls"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 var errUnsupportedOperation = errors.New("Unsupported operation")
@@ -23,13 +24,13 @@ var errUnsupportedOperation = errors.New("Unsupported operation")
 func Run(ctx context.Context, src, dst string, recursive bool, fsys afero.Fs) error {
 	srcParsed, err := url.Parse(src)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to parse src url: %w", err)
 	}
 	dstParsed, err := url.Parse(dst)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to parse dst url: %w", err)
 	}
-	projectRef, err := utils.LoadProjectRef(fsys)
+	projectRef, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
@@ -47,7 +48,7 @@ func Run(ctx context.Context, src, dst string, recursive bool, fsys afero.Fs) er
 		return errors.New("Copying between buckets is not supported")
 	}
 	utils.CmdSuggestion = fmt.Sprintf("Run %s to copy between local directories.", utils.Aqua("cp -r <src> <dst>"))
-	return errUnsupportedOperation
+	return errors.New(errUnsupportedOperation)
 }
 
 func DownloadStorageObjectAll(ctx context.Context, projectRef, remotePath, localPath string, fsys afero.Fs) error {
@@ -96,14 +97,14 @@ func UploadStorageObjectAll(ctx context.Context, projectRef, remotePath, localPa
 	baseName := filepath.Base(localPath)
 	return afero.Walk(fsys, localPath, func(filePath string, info fs.FileInfo, err error) error {
 		if err != nil {
-			return err
+			return errors.New(err)
 		}
 		if !info.Mode().IsRegular() {
 			return nil
 		}
 		relPath, err := filepath.Rel(localPath, filePath)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to resolve relative path: %w", err)
 		}
 		dstPath := remotePath
 		// Copying single file
diff --git a/internal/storage/ls/ls.go b/internal/storage/ls/ls.go
index 079dd74b..2cb9f974 100644
--- a/internal/storage/ls/ls.go
+++ b/internal/storage/ls/ls.go
@@ -10,7 +10,7 @@ import (
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/storage"
 	"github.com/supabase/cli/internal/storage/client"
-	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 func Run(ctx context.Context, objectPath string, recursive bool, fsys afero.Fs) error {
@@ -18,7 +18,7 @@ func Run(ctx context.Context, objectPath string, recursive bool, fsys afero.Fs)
 	if err != nil {
 		return err
 	}
-	projectRef, err := utils.LoadProjectRef(fsys)
+	projectRef, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
diff --git a/internal/storage/mv/mv.go b/internal/storage/mv/mv.go
index 1fe1b440..44d61b2f 100644
--- a/internal/storage/mv/mv.go
+++ b/internal/storage/mv/mv.go
@@ -2,17 +2,17 @@ package mv
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"path"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/storage"
 	"github.com/supabase/cli/internal/storage/client"
 	"github.com/supabase/cli/internal/storage/ls"
-	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 var (
@@ -29,17 +29,17 @@ func Run(ctx context.Context, src, dst string, recursive bool, fsys afero.Fs) er
 	if err != nil {
 		return err
 	}
-	projectRef, err := utils.LoadProjectRef(fsys)
+	projectRef, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
 	srcBucket, srcPrefix := storage.SplitBucketPrefix(srcParsed)
 	dstBucket, dstPrefix := storage.SplitBucketPrefix(dstParsed)
 	if len(srcPrefix) == 0 && len(dstPrefix) == 0 {
-		return errMissingPath
+		return errors.New(errMissingPath)
 	}
 	if srcBucket != dstBucket {
-		return errUnsupportedMove
+		return errors.New(errUnsupportedMove)
 	}
 	fmt.Fprintln(os.Stderr, "Moving object:", srcParsed, "=>", dstParsed)
 	data, err := client.MoveStorageObject(ctx, projectRef, srcBucket, srcPrefix, dstPrefix)
diff --git a/internal/storage/rm/rm.go b/internal/storage/rm/rm.go
index ed0cf6e7..cd8f165f 100644
--- a/internal/storage/rm/rm.go
+++ b/internal/storage/rm/rm.go
@@ -2,17 +2,18 @@ package rm
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"os"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/storage"
 	"github.com/supabase/cli/internal/storage/client"
 	"github.com/supabase/cli/internal/storage/cp"
 	"github.com/supabase/cli/internal/storage/ls"
 	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/internal/utils/flags"
 )
 
 var (
@@ -37,14 +38,14 @@ func Run(ctx context.Context, paths []string, recursive bool, fsys afero.Fs) err
 		bucket, prefix := storage.SplitBucketPrefix(remotePath)
 		// Ignore attempts to delete all buckets
 		if len(bucket) == 0 {
-			return errMissingBucket
+			return errors.New(errMissingBucket)
 		}
 		if cp.IsDir(prefix) && !recursive {
-			return errMissingFlag
+			return errors.New(errMissingFlag)
 		}
 		groups[bucket] = append(groups[bucket], prefix)
 	}
-	projectRef, err := utils.LoadProjectRef(fsys)
+	projectRef, err := flags.LoadProjectRef(fsys)
 	if err != nil {
 		return err
 	}
@@ -95,7 +96,7 @@ func RemoveStoragePathAll(ctx context.Context, projectRef, bucket, prefix string
 			return err
 		}
 		if len(paths) == 0 && len(prefix) > 0 {
-			return fmt.Errorf("%w: %s/%s", errMissingObject, bucket, prefix)
+			return errors.Errorf("%w: %s/%s", errMissingObject, bucket, prefix)
 		}
 		var files []string
 		for _, objectName := range paths {
diff --git a/internal/storage/scheme.go b/internal/storage/scheme.go
index aabf2301..96f4e6cd 100644
--- a/internal/storage/scheme.go
+++ b/internal/storage/scheme.go
@@ -1,9 +1,10 @@
 package storage
 
 import (
-	"errors"
 	"net/url"
 	"strings"
+
+	"github.com/go-errors/errors"
 )
 
 const STORAGE_SCHEME = "ss"
@@ -13,10 +14,10 @@ var ErrInvalidURL = errors.New("URL must match pattern ss:///bucket/[prefix]")
 func ParseStorageURL(objectURL string) (string, error) {
 	parsed, err := url.Parse(objectURL)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to parse storage url: %w", err)
 	}
 	if strings.ToLower(parsed.Scheme) != STORAGE_SCHEME || len(parsed.Path) == 0 || len(parsed.Host) > 0 {
-		return "", ErrInvalidURL
+		return "", errors.New(ErrInvalidURL)
 	}
 	return parsed.Path, nil
 }
diff --git a/internal/utils/access_token.go b/internal/utils/access_token.go
index cc2ba8ee..cce87611 100644
--- a/internal/utils/access_token.go
+++ b/internal/utils/access_token.go
@@ -1,11 +1,11 @@
 package utils
 
 import (
-	"errors"
 	"os"
 	"path/filepath"
 	"regexp"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils/credentials"
 	"github.com/zalando/go-keyring"
@@ -14,7 +14,7 @@ import (
 var (
 	AccessTokenPattern = regexp.MustCompile(`^sbp_[a-f0-9]{40}$`)
 	ErrInvalidToken    = errors.New("Invalid access token format. Must be like `sbp_0102...1920`.")
-	ErrMissingToken    = errors.New("Access token not provided. Supply an access token by running " + Aqua("supabase login") + " or setting the SUPABASE_ACCESS_TOKEN environment variable.")
+	ErrMissingToken    = errors.Errorf("Access token not provided. Supply an access token by running %s or setting the SUPABASE_ACCESS_TOKEN environment variable.", Aqua("supabase login"))
 	ErrNotLoggedIn     = errors.New("You were not logged in, nothing to do.")
 )
 
@@ -30,9 +30,9 @@ func LoadAccessTokenFS(fsys afero.Fs) (string, error) {
 		return "", err
 	}
 	if !AccessTokenPattern.MatchString(accessToken) {
-		return "", ErrInvalidToken
+		return "", errors.New(ErrInvalidToken)
 	}
-	return accessToken, err
+	return accessToken, nil
 }
 
 func loadAccessToken(fsys afero.Fs) (string, error) {
@@ -55,9 +55,9 @@ func fallbackLoadToken(fsys afero.Fs) (string, error) {
 	}
 	accessToken, err := afero.ReadFile(fsys, path)
 	if errors.Is(err, os.ErrNotExist) {
-		return "", ErrMissingToken
+		return "", errors.New(ErrMissingToken)
 	} else if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to read access token file: %w", err)
 	}
 	return string(accessToken), nil
 }
@@ -65,7 +65,7 @@ func fallbackLoadToken(fsys afero.Fs) (string, error) {
 func SaveAccessToken(accessToken string, fsys afero.Fs) error {
 	// Validate access token
 	if !AccessTokenPattern.MatchString(accessToken) {
-		return ErrInvalidToken
+		return errors.New(ErrInvalidToken)
 	}
 	// Save to native credentials store
 	if err := credentials.Set(AccessTokenKey, accessToken); err == nil {
@@ -83,7 +83,10 @@ func fallbackSaveToken(accessToken string, fsys afero.Fs) error {
 	if err := MkdirIfNotExistFS(fsys, filepath.Dir(path)); err != nil {
 		return err
 	}
-	return afero.WriteFile(fsys, path, []byte(accessToken), 0600)
+	if err := afero.WriteFile(fsys, path, []byte(accessToken), 0600); err != nil {
+		return errors.Errorf("failed to save access token file: %w", err)
+	}
+	return nil
 }
 
 func DeleteAccessToken(fsys afero.Fs) error {
@@ -99,9 +102,11 @@ func DeleteAccessToken(fsys afero.Fs) error {
 	// Fallback not found, delete from native credentials store
 	err := credentials.Delete(AccessTokenKey)
 	if errors.Is(err, credentials.ErrNotSupported) || errors.Is(err, keyring.ErrNotFound) {
-		return ErrNotLoggedIn
+		return errors.New(ErrNotLoggedIn)
+	} else if err != nil {
+		return errors.Errorf("failed to delete access token from keyring: %w", err)
 	}
-	return err
+	return nil
 }
 
 func fallbackDeleteToken(fsys afero.Fs) error {
@@ -109,13 +114,16 @@ func fallbackDeleteToken(fsys afero.Fs) error {
 	if err != nil {
 		return err
 	}
-	return fsys.Remove(path)
+	if err := fsys.Remove(path); err != nil {
+		return errors.Errorf("failed to remove access token file: %w", err)
+	}
+	return nil
 }
 
 func getAccessTokenPath() (string, error) {
 	home, err := os.UserHomeDir()
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to get $HOME directory: %w", err)
 	}
 	// TODO: fallback to workdir
 	return filepath.Join(home, ".supabase", AccessTokenKey), nil
diff --git a/internal/utils/api.go b/internal/utils/api.go
index ef34978b..78d99ff8 100644
--- a/internal/utils/api.go
+++ b/internal/utils/api.go
@@ -12,6 +12,7 @@ import (
 	"net/textproto"
 	"sync"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/viper"
 	supabase "github.com/supabase/cli/pkg/api"
 )
@@ -69,9 +70,9 @@ func FallbackLookupIP(ctx context.Context, host string) ([]string, error) {
 		}
 	}
 	if len(resolved) == 0 {
-		err = fmt.Errorf("failed to locate valid IP for %s; resolves to %#v", host, data.Answer)
+		return nil, errors.Errorf("failed to locate valid IP for %s; resolves to %#v", host, data.Answer)
 	}
-	return resolved, err
+	return resolved, nil
 }
 
 func ResolveCNAME(ctx context.Context, host string) (string, error) {
@@ -93,9 +94,9 @@ func ResolveCNAME(ctx context.Context, host string) (string, error) {
 	serialized, err := json.MarshalIndent(data.Answer, "", "    ")
 	if err != nil {
 		// we ignore the error (not great), and use the underlying struct in our error message
-		return "", fmt.Errorf("failed to locate appropriate CNAME record for %s; resolves to %+v", host, data.Answer)
+		return "", errors.Errorf("failed to locate appropriate CNAME record for %s; resolves to %+v", host, data.Answer)
 	}
-	return "", fmt.Errorf("failed to locate appropriate CNAME record for %s; resolves to %+v", host, serialized)
+	return "", errors.Errorf("failed to locate appropriate CNAME record for %s; resolves to %+v", host, serialized)
 }
 
 func WithTraceContext(ctx context.Context) context.Context {
@@ -158,13 +159,17 @@ func withFallbackDNS(dialContext DialContextFunc) DialContextFunc {
 	dnsOverHttps := func(ctx context.Context, network, address string) (net.Conn, error) {
 		host, port, err := net.SplitHostPort(address)
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to split host port: %w", err)
 		}
 		ip, err := FallbackLookupIP(ctx, host)
 		if err != nil {
 			return nil, err
 		}
-		return dialContext(ctx, network, net.JoinHostPort(ip[0], port))
+		conn, err := dialContext(ctx, network, net.JoinHostPort(ip[0], port))
+		if err != nil {
+			return nil, errors.Errorf("failed to dial fallback: %w", err)
+		}
+		return conn, nil
 	}
 	if DNSResolver.Value == DNS_OVER_HTTPS {
 		return dnsOverHttps
@@ -174,10 +179,13 @@ func withFallbackDNS(dialContext DialContextFunc) DialContextFunc {
 		// Workaround when pure Go DNS resolver fails https://github.com/golang/go/issues/12524
 		if err, ok := err.(net.Error); ok && err.Timeout() {
 			if conn, err := dnsOverHttps(ctx, network, address); err == nil {
-				return conn, err
+				return conn, nil
 			}
 		}
-		return conn, err
+		if err != nil {
+			return nil, errors.Errorf("failed to dial native: %w", err)
+		}
+		return conn, nil
 	}
 	return nativeWithFallback
 }
diff --git a/internal/utils/config.go b/internal/utils/config.go
index d7118895..be8a59f9 100644
--- a/internal/utils/config.go
+++ b/internal/utils/config.go
@@ -3,7 +3,6 @@ package utils
 import (
 	"bytes"
 	_ "embed"
-	"errors"
 	"fmt"
 	"os"
 	"path/filepath"
@@ -13,6 +12,7 @@ import (
 
 	"github.com/BurntSushi/toml"
 	"github.com/docker/go-units"
+	"github.com/go-errors/errors"
 	"github.com/joho/godotenv"
 	"github.com/spf13/afero"
 	"github.com/spf13/viper"
@@ -388,11 +388,11 @@ func LoadConfigFS(fsys afero.Fs) error {
 	// Load default values
 	var buf bytes.Buffer
 	if err := initConfigTemplate.Execute(&buf, nil); err != nil {
-		return err
+		return errors.Errorf("failed to initialise config template: %w", err)
 	}
 	dec := toml.NewDecoder(&buf)
 	if _, err := dec.Decode(&Config); err != nil {
-		return err
+		return errors.Errorf("failed to decode config template: %w", err)
 	}
 	// Load user defined config
 	if metadata, err := toml.DecodeFS(afero.NewIOFS(fsys), ConfigPath, &Config); err != nil {
@@ -401,16 +401,16 @@ func LoadConfigFS(fsys afero.Fs) error {
 		if osErr != nil {
 			cwd = "current directory"
 		}
-		return fmt.Errorf("cannot read config in %s: %w", cwd, err)
+		return errors.Errorf("cannot read config in %s: %w", Bold(cwd), err)
 	} else if undecoded := metadata.Undecoded(); len(undecoded) > 0 {
 		fmt.Fprintf(os.Stderr, "Unknown config fields: %+v\n", undecoded)
 	}
 	// Load secrets from .env file
 	if err := godotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {
-		return err
+		return errors.Errorf("failed to load %s: %w", Bold(".env"), err)
 	}
 	if err := viper.Unmarshal(&Config); err != nil {
-		return err
+		return errors.Errorf("failed to parse env to config: %w", err)
 	}
 
 	// Process decoded TOML.
@@ -468,20 +468,20 @@ func LoadConfigFS(fsys afero.Fs) error {
 				Config.Db.Image = Pg15Image[:index+1] + string(version)
 			}
 		default:
-			return fmt.Errorf("Failed reading config: Invalid %s: %v.", Aqua("db.major_version"), Config.Db.MajorVersion)
+			return errors.Errorf("Failed reading config: Invalid %s: %v.", Aqua("db.major_version"), Config.Db.MajorVersion)
 		}
 		// Validate pooler config
 		if Config.Db.Pooler.Enabled {
 			allowed := []PoolMode{TransactionMode, SessionMode}
 			if !SliceContains(allowed, Config.Db.Pooler.PoolMode) {
-				return fmt.Errorf("Invalid config for db.pooler.pool_mode. Must be one of: %v", allowed)
+				return errors.Errorf("Invalid config for db.pooler.pool_mode. Must be one of: %v", allowed)
 			}
 		}
 		// Validate realtime config
 		if Config.Realtime.Enabled {
 			allowed := []AddressFamily{AddressIPv6, AddressIPv4}
 			if !SliceContains(allowed, Config.Realtime.IpVersion) {
-				return fmt.Errorf("Invalid config for realtime.ip_version. Must be one of: %v", allowed)
+				return errors.Errorf("Invalid config for realtime.ip_version. Must be one of: %v", allowed)
 			}
 		}
 		// Validate storage config
@@ -516,7 +516,7 @@ func LoadConfigFS(fsys afero.Fs) error {
 			for _, tmpl := range Config.Auth.Email.Template {
 				if len(tmpl.ContentPath) > 0 {
 					if _, err := fsys.Stat(tmpl.ContentPath); err != nil {
-						return err
+						return errors.Errorf("failed to read file info: %w", err)
 					}
 				}
 			}
@@ -595,10 +595,10 @@ func LoadConfigFS(fsys afero.Fs) error {
 					continue
 				}
 				if provider.ClientId == "" {
-					return fmt.Errorf("Missing required field in config: auth.external.%s.client_id", ext)
+					return errors.Errorf("Missing required field in config: auth.external.%s.client_id", ext)
 				}
 				if provider.Secret == "" {
-					return fmt.Errorf("Missing required field in config: auth.external.%s.secret", ext)
+					return errors.Errorf("Missing required field in config: auth.external.%s.secret", ext)
 				}
 				if provider.ClientId, err = maybeLoadEnv(provider.ClientId); err != nil {
 					return err
@@ -641,7 +641,7 @@ func LoadConfigFS(fsys afero.Fs) error {
 			break
 		default:
 			allowed := []LogflareBackend{LogflarePostgres, LogflareBigQuery}
-			return fmt.Errorf("Invalid config for analytics.backend. Must be one of: %v", allowed)
+			return errors.Errorf("Invalid config for analytics.backend. Must be one of: %v", allowed)
 		}
 	}
 	return nil
@@ -658,7 +658,7 @@ func maybeLoadEnv(s string) (string, error) {
 		return value, nil
 	}
 
-	return "", fmt.Errorf(`Error evaluating "%s": environment variable %s is unset.`, s, envName)
+	return "", errors.Errorf(`Error evaluating "%s": environment variable %s is unset.`, s, envName)
 }
 
 func sanitizeProjectId(src string) string {
@@ -678,7 +678,7 @@ func InitConfig(params InitParams, fsys afero.Fs) error {
 	if len(params.ProjectId) == 0 {
 		cwd, err := os.Getwd()
 		if err != nil {
-			return err
+			return errors.Errorf("failed to get working directory: %w", err)
 		}
 		params.ProjectId = filepath.Base(cwd)
 	}
@@ -687,13 +687,16 @@ func InitConfig(params InitParams, fsys afero.Fs) error {
 	if err := MkdirIfNotExistFS(fsys, filepath.Dir(ConfigPath)); err != nil {
 		return err
 	}
-	f, err := fsys.OpenFile(ConfigPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+	f, err := fsys.OpenFile(ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to create config file: %w", err)
 	}
 	defer f.Close()
 	// Update from template
-	return initConfigTemplate.Execute(f, params)
+	if err := initConfigTemplate.Execute(f, params); err != nil {
+		return errors.Errorf("failed to initialise config: %w", err)
+	}
+	return nil
 }
 
 func WriteConfig(fsys afero.Fs, _test bool) error {
diff --git a/internal/utils/connect.go b/internal/utils/connect.go
index d9a1f5a3..895cfc2d 100644
--- a/internal/utils/connect.go
+++ b/internal/utils/connect.go
@@ -2,7 +2,6 @@ package utils
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"net"
 	"net/url"
@@ -10,6 +9,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgx/v4"
 	"github.com/spf13/viper"
@@ -17,9 +17,13 @@ import (
 )
 
 func isDialError(err error) bool {
-	inner := errors.Unwrap(err)
-	opErr, ok := inner.(*net.OpError)
-	return ok && opErr.Op == "dial"
+	for err != nil {
+		if opErr, ok := err.(*net.OpError); ok && opErr.Op == "dial" {
+			return true
+		}
+		err = errors.Unwrap(err)
+	}
+	return false
 }
 
 func ToPostgresURL(config pgconn.Config) string {
@@ -93,7 +97,7 @@ func ConnectByUrl(ctx context.Context, url string, options ...func(*pgx.ConnConf
 	// Parse connection url
 	config, err := pgx.ParseConfig(url)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to parse postgres url: %w", err)
 	}
 	// Apply config overrides
 	for _, op := range options {
@@ -103,7 +107,11 @@ func ConnectByUrl(ctx context.Context, url string, options ...func(*pgx.ConnConf
 		debug.SetupPGX(config)
 	}
 	// Connect to database
-	return pgx.ConnectConfig(ctx, config)
+	conn, err := pgx.ConnectConfig(ctx, config)
+	if err != nil {
+		return nil, errors.Errorf("failed to connect to postgres: %w", err)
+	}
+	return conn, nil
 }
 
 func ConnectByConfig(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error) {
diff --git a/internal/utils/credentials/store.go b/internal/utils/credentials/store.go
index a2559036..7425ddae 100644
--- a/internal/utils/credentials/store.go
+++ b/internal/utils/credentials/store.go
@@ -2,9 +2,9 @@ package credentials
 
 import (
 	"bytes"
-	"errors"
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/zalando/go-keyring"
 )
 
@@ -17,7 +17,11 @@ func Get(project string) (string, error) {
 	if err := assertKeyringSupported(); err != nil {
 		return "", err
 	}
-	return keyring.Get(namespace, project)
+	val, err := keyring.Get(namespace, project)
+	if err != nil {
+		return "", errors.Errorf("failed to load credentials: %w", err)
+	}
+	return val, nil
 }
 
 // Stores the password of a project and username
@@ -25,7 +29,10 @@ func Set(project, password string) error {
 	if err := assertKeyringSupported(); err != nil {
 		return err
 	}
-	return keyring.Set(namespace, project, password)
+	if err := keyring.Set(namespace, project, password); err != nil {
+		return errors.Errorf("failed to set credentials: %w", err)
+	}
+	return nil
 }
 
 // Erases the stored password of a project and username
@@ -33,13 +40,16 @@ func Delete(project string) error {
 	if err := assertKeyringSupported(); err != nil {
 		return err
 	}
-	return keyring.Delete(namespace, project)
+	if err := keyring.Delete(namespace, project); err != nil {
+		return errors.Errorf("failed to delete credentials: %w", err)
+	}
+	return nil
 }
 
 func assertKeyringSupported() error {
 	// Suggested check: https://github.com/microsoft/WSL/issues/423
 	if f, err := os.ReadFile("/proc/sys/kernel/osrelease"); err == nil && bytes.Contains(f, []byte("WSL")) {
-		return ErrNotSupported
+		return errors.New(ErrNotSupported)
 	}
 	return nil
 }
diff --git a/internal/utils/deno.go b/internal/utils/deno.go
index 3ece956a..a1af6e46 100644
--- a/internal/utils/deno.go
+++ b/internal/utils/deno.go
@@ -8,7 +8,6 @@ import (
 	"embed"
 	"encoding/hex"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"io"
 	"io/fs"
@@ -20,6 +19,7 @@ import (
 	"runtime"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 )
 
@@ -218,7 +218,7 @@ type ImportMap struct {
 func NewImportMap(path string, fsys afero.Fs) (*ImportMap, error) {
 	contents, err := fsys.Open(path)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to load import map: %w", err)
 	}
 	defer contents.Close()
 	return NewFromReader(contents)
@@ -228,7 +228,7 @@ func NewFromReader(r io.Reader) (*ImportMap, error) {
 	decoder := json.NewDecoder(r)
 	importMap := &ImportMap{}
 	if err := decoder.Decode(importMap); err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to parse import map: %w", err)
 	}
 	return importMap, nil
 }
@@ -332,7 +332,7 @@ func AbsImportMapPath(importMapPath, slug string, fsys afero.Fs) (string, error)
 		return "", err
 	}
 	if f, err := fsys.Stat(resolved); err != nil {
-		return "", fmt.Errorf("Failed to read import map: %w", err)
+		return "", errors.Errorf("Failed to read import map: %w", err)
 	} else if f.IsDir() {
 		return "", errors.New("Importing directory is unsupported: " + resolved)
 	}
@@ -354,11 +354,11 @@ func BindImportMap(hostImportMapPath, dockerImportMapPath string, fsys afero.Fs)
 	if len(binds) > 0 {
 		cwd, err := os.Getwd()
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to get working directory: %w", err)
 		}
 		contents, err := json.MarshalIndent(resolved, "", "    ")
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to encode json: %w", err)
 		}
 		// Rewrite import map to temporary host path
 		hostImportMapPath = AbsTempImportMapPath(cwd, hostImportMapPath)
diff --git a/internal/utils/deno_darwin.go b/internal/utils/deno_darwin.go
index cfe3d5cf..fe0b89d1 100644
--- a/internal/utils/deno_darwin.go
+++ b/internal/utils/deno_darwin.go
@@ -3,8 +3,9 @@
 package utils
 
 import (
-	"fmt"
 	"syscall"
+
+	"github.com/go-errors/errors"
 )
 
 func getDenoAssetFileName() (string, error) {
@@ -19,7 +20,7 @@ func getDenoAssetFileName() (string, error) {
 			// Running on Intel Mac.
 			return "deno-x86_64-apple-darwin.zip", nil
 		} else {
-			return "", fmt.Errorf("failed to determine OS triple: %w", err)
+			return "", errors.Errorf("failed to determine OS triple: %w", err)
 		}
 	} else {
 		// Running on Apple Silicon.
diff --git a/internal/utils/docker.go b/internal/utils/docker.go
index a7f0890c..986c2599 100644
--- a/internal/utils/docker.go
+++ b/internal/utils/docker.go
@@ -6,7 +6,6 @@ import (
 	"context"
 	"encoding/base64"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"io"
 	"log"
@@ -31,6 +30,7 @@ import (
 	"github.com/docker/docker/errdefs"
 	"github.com/docker/docker/pkg/jsonmessage"
 	"github.com/docker/docker/pkg/stdcopy"
+	"github.com/go-errors/errors"
 	"github.com/spf13/viper"
 )
 
@@ -53,7 +53,7 @@ func AssertDockerIsRunning(ctx context.Context) error {
 		if client.IsErrConnectionFailed(err) {
 			CmdSuggestion = suggestDockerInstall
 		}
-		return NewError(err.Error())
+		return errors.Errorf("failed to ping docker daemon: %w", err)
 	}
 
 	return nil
@@ -80,6 +80,9 @@ func DockerNetworkCreateIfNotExists(ctx context.Context, networkId string) error
 	if errdefs.IsConflict(err) || errors.Is(err, podman.ErrNetworkExists) {
 		return nil
 	}
+	if err != nil {
+		return errors.Errorf("failed to create docker network: %w", err)
+	}
 	return err
 }
 
@@ -135,24 +138,24 @@ func DockerAddFile(ctx context.Context, container string, fileName string, conte
 	})
 
 	if err != nil {
-		return fmt.Errorf("failed to copy file: %v", err)
+		return errors.Errorf("failed to copy file: %w", err)
 	}
 
 	_, err = tw.Write(content)
 
 	if err != nil {
-		return fmt.Errorf("failed to copy file: %v", err)
+		return errors.Errorf("failed to copy file: %w", err)
 	}
 
 	err = tw.Close()
 
 	if err != nil {
-		return fmt.Errorf("failed to copy file: %v", err)
+		return errors.Errorf("failed to copy file: %w", err)
 	}
 
 	err = Docker.CopyToContainer(ctx, container, "/tmp", &buf, types.CopyToContainerOptions{})
 	if err != nil {
-		return fmt.Errorf("failed to copy file: %v", err)
+		return errors.Errorf("failed to copy file: %w", err)
 	}
 	return nil
 }
@@ -167,7 +170,7 @@ func GetRegistryAuth() string {
 	registryOnce.Do(func() {
 		config := dockerConfig.LoadDefaultConfigFile(os.Stderr)
 		// Ref: https://docs.docker.com/engine/api/sdk/examples/#pull-an-image-with-authentication
-		auth, err := config.GetAuthConfig(getRegistry())
+		auth, err := config.GetAuthConfig(GetRegistry())
 		if err != nil {
 			fmt.Fprintln(os.Stderr, "Failed to load registry credentials:", err)
 			return
@@ -185,7 +188,7 @@ func GetRegistryAuth() string {
 // Defaults to Supabase public ECR for faster image pull
 const defaultRegistry = "public.ecr.aws"
 
-func getRegistry() string {
+func GetRegistry() string {
 	registry := viper.GetString("INTERNAL_IMAGE_REGISTRY")
 	if len(registry) == 0 {
 		return defaultRegistry
@@ -194,7 +197,7 @@ func getRegistry() string {
 }
 
 func GetRegistryImageUrl(imageName string) string {
-	registry := getRegistry()
+	registry := GetRegistry()
 	if registry == "docker.io" {
 		return imageName
 	}
@@ -209,10 +212,13 @@ func DockerImagePull(ctx context.Context, image string, w io.Writer) error {
 		RegistryAuth: GetRegistryAuth(),
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to pull docker image: %w", err)
 	}
 	defer out.Close()
-	return jsonmessage.DisplayJSONMessagesToStream(out, streams.NewOut(w), nil)
+	if err := jsonmessage.DisplayJSONMessagesToStream(out, streams.NewOut(w), nil); err != nil {
+		return errors.Errorf("failed to display json stream: %w", err)
+	}
+	return nil
 }
 
 // Used by unit tests
@@ -238,7 +244,7 @@ func DockerPullImageIfNotCached(ctx context.Context, imageName string) error {
 	if _, _, err := Docker.ImageInspectWithRaw(ctx, imageUrl); err == nil {
 		return nil
 	} else if !client.IsErrNotFound(err) {
-		return err
+		return errors.Errorf("failed to inspect docker image: %w", err)
 	}
 	return DockerImagePullWithRetry(ctx, imageUrl, 2)
 }
@@ -276,7 +282,7 @@ func DockerStart(ctx context.Context, config container.Config, hostConfig contai
 		for _, bind := range hostConfig.Binds {
 			spec, err := loader.ParseVolume(bind)
 			if err != nil {
-				return "", err
+				return "", errors.Errorf("failed to parse docker volume: %w", err)
 			}
 			if spec.Type != string(mount.TypeVolume) {
 				binds = append(binds, bind)
@@ -287,14 +293,14 @@ func DockerStart(ctx context.Context, config container.Config, hostConfig contai
 	// Create container from image
 	resp, err := Docker.ContainerCreate(ctx, &config, &hostConfig, &networkingConfig, nil, containerName)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to create docker container: %w", err)
 	}
 	// Track container id for cleanup
 	Containers = append(Containers, resp.ID)
 	for _, bind := range hostConfig.Binds {
 		spec, err := loader.ParseVolume(bind)
 		if err != nil {
-			return "", err
+			return "", errors.Errorf("failed to parse docker volume: %w", err)
 		}
 		// Track named volumes for cleanup
 		if len(spec.Source) > 0 && spec.Type == string(mount.TypeVolume) {
@@ -316,6 +322,7 @@ func DockerStart(ctx context.Context, config container.Config, hostConfig contai
 			}
 			CmdSuggestion += fmt.Sprintf("\n%s a different %s port in %s", prefix, name, Bold(ConfigPath))
 		}
+		err = errors.Errorf("failed to start docker container: %w", err)
 	}
 	return resp.ID, err
 }
@@ -368,19 +375,19 @@ func DockerStreamLogs(ctx context.Context, container string, stdout, stderr io.W
 		Follow:     true,
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to read docker logs: %w", err)
 	}
 	defer logs.Close()
 	if _, err := stdcopy.StdCopy(stdout, stderr, logs); err != nil {
-		return err
+		return errors.Errorf("failed to copy docker logs: %w", err)
 	}
 	// Check exit code
 	resp, err := Docker.ContainerInspect(ctx, container)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to inspect docker container: %w", err)
 	}
 	if resp.State.ExitCode > 0 {
-		return fmt.Errorf("error running container: exit %d", resp.State.ExitCode)
+		return errors.Errorf("error running container: exit %d", resp.State.ExitCode)
 	}
 	return nil
 }
@@ -406,22 +413,22 @@ func DockerExecOnceWithStream(ctx context.Context, container, workdir string, en
 		AttachStdout: true,
 	})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to exec docker create: %w", err)
 	}
 	// Read exec output
 	resp, err := Docker.ContainerExecAttach(ctx, exec.ID, types.ExecStartCheck{})
 	if err != nil {
-		return err
+		return errors.Errorf("failed to exec docker attach: %w", err)
 	}
 	defer resp.Close()
 	// Capture error details
 	if _, err := stdcopy.StdCopy(stdout, stderr, resp.Reader); err != nil {
-		return err
+		return errors.Errorf("failed to copy docker logs: %w", err)
 	}
 	// Get the exit code
 	iresp, err := Docker.ContainerExecInspect(ctx, exec.ID)
 	if err != nil {
-		return err
+		return errors.Errorf("failed to exec docker inspect: %w", err)
 	}
 	if iresp.ExitCode > 0 {
 		err = errors.New("error executing command")
diff --git a/internal/utils/enum.go b/internal/utils/enum.go
index 1245c3c8..426c45cb 100644
--- a/internal/utils/enum.go
+++ b/internal/utils/enum.go
@@ -3,6 +3,8 @@ package utils
 import (
 	"fmt"
 	"strings"
+
+	"github.com/go-errors/errors"
 )
 
 // Ref: https://github.com/spf13/pflag/issues/236#issuecomment-931600452
@@ -25,7 +27,7 @@ func (a *EnumFlag) Set(p string) error {
 		return false
 	}
 	if !isIncluded(a.Allowed, p) {
-		return fmt.Errorf("must be one of [ %s ]", strings.Join(a.Allowed, " | "))
+		return errors.Errorf("must be one of [ %s ]", strings.Join(a.Allowed, " | "))
 	}
 	a.Value = p
 	return nil
diff --git a/internal/utils/flags/db_url.go b/internal/utils/flags/db_url.go
index ee93f5dd..702ee4c1 100644
--- a/internal/utils/flags/db_url.go
+++ b/internal/utils/flags/db_url.go
@@ -3,6 +3,7 @@ package flags
 import (
 	"os"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/spf13/afero"
 	"github.com/spf13/pflag"
@@ -47,7 +48,7 @@ func ParseDatabaseConfig(flagSet *pflag.FlagSet, fsys afero.Fs) error {
 		if flag := flagSet.Lookup("db-url"); flag != nil {
 			config, err := pgconn.ParseConfig(flag.Value.String())
 			if err != nil {
-				return err
+				return errors.Errorf("failed to parse connection string: %w", err)
 			}
 			DbConfig = *config
 		}
@@ -61,7 +62,7 @@ func ParseDatabaseConfig(flagSet *pflag.FlagSet, fsys afero.Fs) error {
 		DbConfig.Password = utils.Config.Db.Password
 		DbConfig.Database = "postgres"
 	case linked:
-		projectRef, err := utils.LoadProjectRef(fsys)
+		projectRef, err := LoadProjectRef(fsys)
 		if err != nil {
 			return err
 		}
@@ -75,7 +76,7 @@ func ParseDatabaseConfig(flagSet *pflag.FlagSet, fsys afero.Fs) error {
 		if err != nil {
 			return err
 		}
-		projectRef, err := utils.LoadProjectRef(fsys)
+		projectRef, err := LoadProjectRef(fsys)
 		if err != nil {
 			return err
 		}
diff --git a/internal/utils/flags/project_ref.go b/internal/utils/flags/project_ref.go
index 3fef7338..91f67a62 100644
--- a/internal/utils/flags/project_ref.go
+++ b/internal/utils/flags/project_ref.go
@@ -3,12 +3,12 @@ package flags
 import (
 	"bufio"
 	"bytes"
-	"errors"
 	"fmt"
 	"io"
 	"os"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/spf13/viper"
 	"github.com/supabase/cli/internal/utils"
@@ -26,17 +26,14 @@ func ParseProjectRef(fsys afero.Fs) error {
 		return utils.AssertProjectRefIsValid(ProjectRef)
 	}
 	// Followed by linked ref file
-	if projectRefBytes, err := afero.ReadFile(fsys, utils.ProjectRefPath); err == nil {
-		ProjectRef = string(bytes.TrimSpace(projectRefBytes))
-		return utils.AssertProjectRefIsValid(ProjectRef)
-	} else if !errors.Is(err, os.ErrNotExist) {
+	if _, err := LoadProjectRef(fsys); !errors.Is(err, utils.ErrNotLinked) {
 		return err
 	}
 	// Prompt as the last resort
 	if term.IsTerminal(int(os.Stdin.Fd())) {
 		return promptProjectRef(os.Stdin)
 	}
-	return utils.ErrNotLinked
+	return errors.New(utils.ErrNotLinked)
 }
 
 func promptProjectRef(stdin io.Reader) error {
@@ -46,8 +43,22 @@ Enter your project ref: `, utils.GetSupabaseDashboardURL())
 	scanner := bufio.NewScanner(stdin)
 	scanner.Scan()
 	if err := scanner.Err(); err != nil {
-		return err
+		return errors.Errorf("failed to read project ref: %w", err)
 	}
 	ProjectRef = strings.TrimSpace(scanner.Text())
 	return utils.AssertProjectRefIsValid(ProjectRef)
 }
+
+func LoadProjectRef(fsys afero.Fs) (string, error) {
+	projectRefBytes, err := afero.ReadFile(fsys, utils.ProjectRefPath)
+	if errors.Is(err, os.ErrNotExist) {
+		return "", errors.New(utils.ErrNotLinked)
+	} else if err != nil {
+		return "", errors.Errorf("failed to load project ref: %w", err)
+	}
+	ProjectRef := string(bytes.TrimSpace(projectRefBytes))
+	if err := utils.AssertProjectRefIsValid(ProjectRef); err != nil {
+		return "", err
+	}
+	return ProjectRef, nil
+}
diff --git a/internal/utils/http.go b/internal/utils/http.go
index b4648bc9..4aba1043 100644
--- a/internal/utils/http.go
+++ b/internal/utils/http.go
@@ -4,11 +4,11 @@ import (
 	"bytes"
 	"context"
 	"encoding/json"
-	"fmt"
 	"io"
 	"net/http"
 	"time"
 
+	"github.com/go-errors/errors"
 	openapi "github.com/supabase/cli/pkg/api"
 )
 
@@ -19,7 +19,7 @@ func JsonResponse[T any](ctx context.Context, method, url string, reqBody any, r
 	if reqBody != nil {
 		enc := json.NewEncoder(&body)
 		if err := enc.Encode(reqBody); err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to encode request body: %w", err)
 		}
 		reqEditors = append(reqEditors, func(ctx context.Context, req *http.Request) error {
 			req.Header.Set("Content-Type", "application/json")
@@ -29,7 +29,7 @@ func JsonResponse[T any](ctx context.Context, method, url string, reqBody any, r
 	// Creates request
 	req, err := http.NewRequestWithContext(ctx, method, url, &body)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to initialise http request: %w", err)
 	}
 	for _, edit := range reqEditors {
 		if err := edit(ctx, req); err != nil {
@@ -40,21 +40,21 @@ func JsonResponse[T any](ctx context.Context, method, url string, reqBody any, r
 	// Sends request
 	resp, err := httpClient.Do(req)
 	if err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to execute http request: %w", err)
 	}
 	defer resp.Body.Close()
 	if resp.StatusCode != http.StatusOK {
 		data, err := io.ReadAll(resp.Body)
 		if err != nil {
-			return nil, err
+			return nil, errors.Errorf("failed to read response body: %w", err)
 		}
-		return nil, fmt.Errorf("Error status %d: %s", resp.StatusCode, data)
+		return nil, errors.Errorf("Error status %d: %s", resp.StatusCode, data)
 	}
 	// Parses response
 	var data T
 	dec := json.NewDecoder(resp.Body)
 	if err := dec.Decode(&data); err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to parse response body: %w", err)
 	}
 	return &data, nil
 }
@@ -62,7 +62,7 @@ func JsonResponse[T any](ctx context.Context, method, url string, reqBody any, r
 func TextResponse(ctx context.Context, method, url string, body io.Reader, reqEditors ...openapi.RequestEditorFn) (string, error) {
 	req, err := http.NewRequestWithContext(ctx, method, url, body)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to initialise http request: %w", err)
 	}
 	for _, edit := range reqEditors {
 		if err := edit(ctx, req); err != nil {
@@ -73,15 +73,15 @@ func TextResponse(ctx context.Context, method, url string, body io.Reader, reqEd
 	// Sends request
 	resp, err := httpClient.Do(req)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to execute http request: %w", err)
 	}
 	defer resp.Body.Close()
 	data, err := io.ReadAll(resp.Body)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to read response body: %w", err)
 	}
 	if resp.StatusCode != http.StatusOK {
-		return "", fmt.Errorf("Error status %d: %s", resp.StatusCode, body)
+		return "", errors.Errorf("Error status %d: %s", resp.StatusCode, body)
 	}
 	return string(data), nil
 }
diff --git a/internal/utils/misc.go b/internal/utils/misc.go
index c77dad69..215ef037 100644
--- a/internal/utils/misc.go
+++ b/internal/utils/misc.go
@@ -1,25 +1,24 @@
 package utils
 
 import (
-	"bytes"
 	"context"
 	_ "embed"
-	"errors"
-	"fmt"
 	"os"
 	"path/filepath"
 	"regexp"
-	"runtime"
-	"strings"
 	"time"
 
 	"github.com/docker/docker/client"
+	"github.com/go-errors/errors"
 	"github.com/go-git/go-git/v5"
 	"github.com/spf13/afero"
 )
 
-// Version is assigned using `-ldflags` https://stackoverflow.com/q/11354518.
-var Version string
+// Assigned using `-ldflags` https://stackoverflow.com/q/11354518
+var (
+	Version   string
+	SentryDsn string
+)
 
 const (
 	Pg13Image = "supabase/postgres:13.3.0"
@@ -95,7 +94,7 @@ var (
 
 	ProjectRefPattern  = regexp.MustCompile(`^[a-z]{20}$`)
 	UUIDPattern        = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
-	ProjectHostPattern = regexp.MustCompile(`^(db\.)[a-z]{20}\.supabase\.(co|red)$`)
+	ProjectHostPattern = regexp.MustCompile(`^(db\.)([a-z]{20})\.supabase\.(co|red)$`)
 	MigrateFilePattern = regexp.MustCompile(`^([0-9]+)_(.*)\.sql$`)
 	BranchNamePattern  = regexp.MustCompile(`[[:word:]-]+`)
 	FuncSlugPattern    = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]*$`)
@@ -181,9 +180,10 @@ var (
 	SeedDataPath          = filepath.Join(SupabaseDirPath, "seed.sql")
 	CustomRolesPath       = filepath.Join(SupabaseDirPath, "roles.sql")
 
-	ErrNotLinked  = errors.New("Cannot find project ref. Have you run " + Aqua("supabase link") + "?")
-	ErrInvalidRef = errors.New("Invalid project ref format. Must be like `abcdefghijklmnopqrst`.")
-	ErrNotRunning = errors.New(Aqua("supabase start") + " is not running.")
+	ErrNotLinked   = errors.Errorf("Cannot find project ref. Have you run %s?", Aqua("supabase link"))
+	ErrInvalidRef  = errors.New("Invalid project ref format. Must be like `abcdefghijklmnopqrst`.")
+	ErrInvalidSlug = errors.New("Invalid Function name. Must start with at least one letter, and only include alphanumeric characters, underscores, and hyphens. (^[A-Za-z][A-Za-z0-9_-]*$)")
+	ErrNotRunning  = errors.Errorf("%s is not running.", Aqua("supabase start"))
 )
 
 func GetCurrentTimestamp() string {
@@ -194,51 +194,23 @@ func GetCurrentTimestamp() string {
 func GetCurrentBranchFS(fsys afero.Fs) (string, error) {
 	branch, err := afero.ReadFile(fsys, CurrBranchPath)
 	if err != nil {
-		return "", err
+		return "", errors.Errorf("failed to load current branch: %w", err)
 	}
 
 	return string(branch), nil
 }
 
-// TODO: Make all errors use this.
-func NewError(s string) error {
-	// Ask runtime.Callers for up to 5 PCs, excluding runtime.Callers and NewError.
-	pc := make([]uintptr, 5)
-	n := runtime.Callers(2, pc)
-
-	pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
-	frames := runtime.CallersFrames(pc)
-
-	// Loop to get frames.
-	// A fixed number of PCs can expand to an indefinite number of Frames.
-	for {
-		frame, more := frames.Next()
-
-		// Process this frame.
-		//
-		// We're only interested in the stack trace in this repo.
-		if strings.HasPrefix(frame.Function, "github.com/supabase/cli/internal") {
-			s += fmt.Sprintf("\n  in %s:%d", frame.Function, frame.Line)
+func AssertSupabaseDbIsRunning() error {
+	if _, err := Docker.ContainerInspect(context.Background(), DbId); err != nil {
+		if client.IsErrNotFound(err) {
+			return errors.New(ErrNotRunning)
 		}
-
-		// Check whether there are more frames to process after this one.
-		if !more {
-			break
+		if client.IsErrConnectionFailed(err) {
+			CmdSuggestion = suggestDockerInstall
 		}
+		return errors.Errorf("failed to inspect database container: %w", err)
 	}
-
-	return errors.New(s)
-}
-
-func AssertSupabaseDbIsRunning() error {
-	_, err := Docker.ContainerInspect(context.Background(), DbId)
-	if client.IsErrNotFound(err) {
-		return ErrNotRunning
-	}
-	if client.IsErrConnectionFailed(err) {
-		CmdSuggestion = suggestDockerInstall
-	}
-	return err
+	return nil
 }
 
 func IsGitRepo() bool {
@@ -262,7 +234,10 @@ func GetProjectRoot(fsys afero.Fs) (string, error) {
 			break
 		}
 	}
-	return origWd, err
+	if err != nil {
+		return "", errors.Errorf("failed to find project root: %w", err)
+	}
+	return origWd, nil
 }
 
 func IsBranchNameReserved(branch string) bool {
@@ -280,7 +255,7 @@ func MkdirIfNotExist(path string) error {
 
 func MkdirIfNotExistFS(fsys afero.Fs, path string) error {
 	if err := fsys.MkdirAll(path, 0755); err != nil && !errors.Is(err, os.ErrExist) {
-		return err
+		return errors.Errorf("failed to mkdir: %w", err)
 	}
 
 	return nil
@@ -290,14 +265,17 @@ func WriteFile(path string, contents []byte, fsys afero.Fs) error {
 	if err := MkdirIfNotExistFS(fsys, filepath.Dir(path)); err != nil {
 		return err
 	}
-	return afero.WriteFile(fsys, path, contents, 0644)
+	if err := afero.WriteFile(fsys, path, contents, 0644); err != nil {
+		return errors.Errorf("failed to write file: %w", err)
+	}
+	return nil
 }
 
 func AssertSupabaseCliIsSetUpFS(fsys afero.Fs) error {
 	if _, err := fsys.Stat(ConfigPath); errors.Is(err, os.ErrNotExist) {
-		return errors.New("Cannot find " + Bold(ConfigPath) + " in the current directory. Have you set up the project with " + Aqua("supabase init") + "?")
+		return errors.Errorf("Cannot find %s in the current directory. Have you set up the project with %s?", Bold(ConfigPath), Aqua("supabase init"))
 	} else if err != nil {
-		return err
+		return errors.Errorf("failed to read config file: %w", err)
 	}
 
 	return nil
@@ -305,28 +283,14 @@ func AssertSupabaseCliIsSetUpFS(fsys afero.Fs) error {
 
 func AssertProjectRefIsValid(projectRef string) error {
 	if !ProjectRefPattern.MatchString(projectRef) {
-		return ErrInvalidRef
+		return errors.New(ErrInvalidRef)
 	}
 	return nil
 }
 
-func LoadProjectRef(fsys afero.Fs) (string, error) {
-	projectRefBytes, err := afero.ReadFile(fsys, ProjectRefPath)
-	if errors.Is(err, os.ErrNotExist) {
-		return "", ErrNotLinked
-	} else if err != nil {
-		return "", err
-	}
-	projectRef := string(bytes.TrimSpace(projectRefBytes))
-	if !ProjectRefPattern.MatchString(projectRef) {
-		return "", ErrInvalidRef
-	}
-	return projectRef, nil
-}
-
 func ValidateFunctionSlug(slug string) error {
 	if !FuncSlugPattern.MatchString(slug) {
-		return errors.New("Invalid Function name. Must start with at least one letter, and only include alphanumeric characters, underscores, and hyphens. (^[A-Za-z][A-Za-z0-9_-]*$)")
+		return errors.New(ErrInvalidSlug)
 	}
 
 	return nil
diff --git a/internal/utils/output.go b/internal/utils/output.go
index b36568af..9de61c6d 100644
--- a/internal/utils/output.go
+++ b/internal/utils/output.go
@@ -6,6 +6,7 @@ import (
 	"io"
 
 	"github.com/BurntSushi/toml"
+	"github.com/go-errors/errors"
 	"github.com/joho/godotenv"
 	"gopkg.in/yaml.v2"
 )
@@ -35,30 +36,40 @@ func EncodeOutput(format string, w io.Writer, value any) error {
 	case OutputEnv:
 		mapvalue, ok := value.(map[string]string)
 		if !ok {
-			return fmt.Errorf("value is not a map[string]string and can't be encoded as an environment file")
+			return errors.Errorf("value is not a map[string]string and can't be encoded as an environment file")
 		}
 
 		out, err := godotenv.Marshal(mapvalue)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to marshal env map: %w", err)
 		}
 
-		_, err = fmt.Fprintln(w, out)
-		return err
+		if _, err := fmt.Fprintln(w, out); err != nil {
+			return errors.Errorf("failed to write encoded output: %w", err)
+		}
 
 	case OutputJson:
 		enc := json.NewEncoder(w)
 		enc.SetIndent("", "  ")
 
-		return enc.Encode(value)
+		if err := enc.Encode(value); err != nil {
+			return errors.Errorf("failed to output json: %w", err)
+		}
 
 	case OutputYaml:
-		return yaml.NewEncoder(w).Encode(value)
+		enc := yaml.NewEncoder(w)
+		if err := enc.Encode(value); err != nil {
+			return errors.Errorf("failed to output yaml: %w", err)
+		}
 
 	case OutputToml:
-		return toml.NewEncoder(w).Encode(value)
+		enc := toml.NewEncoder(w)
+		if err := enc.Encode(value); err != nil {
+			return errors.Errorf("failed to output toml: %w", err)
+		}
 
 	default:
-		return fmt.Errorf("Unsupported output encoding %q", format)
+		return errors.Errorf("Unsupported output encoding %q", format)
 	}
+	return nil
 }
diff --git a/internal/utils/parser/token.go b/internal/utils/parser/token.go
index 23936e56..018a6f5d 100644
--- a/internal/utils/parser/token.go
+++ b/internal/utils/parser/token.go
@@ -2,14 +2,12 @@ package parser
 
 import (
 	"bufio"
-	"errors"
-	"fmt"
 	"io"
 	"strings"
 	"unicode/utf8"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/viper"
-	"github.com/supabase/cli/internal/utils"
 )
 
 // Equal to `startBufSize` from `bufio/scan.go`
@@ -105,10 +103,10 @@ func Split(sql io.Reader, transform ...func(string) string) (stats []string, err
 	}
 	err = scanner.Err()
 	if err != nil {
-		err = fmt.Errorf("%w\nAfter statement %d: %s", err, len(stats), utils.Aqua(token))
+		err = errors.Errorf("%w\nAfter statement %d: %s", err, len(stats), token)
 	}
 	if errors.Is(err, bufio.ErrTooLong) {
-		err = fmt.Errorf("%w\nTry setting SUPABASE_SCANNER_BUFFER_SIZE=5MB (current size is %dKB)", err, maxbuf>>10)
+		err = errors.Errorf("%w\nTry setting SUPABASE_SCANNER_BUFFER_SIZE=5MB (current size is %dKB)", err, maxbuf>>10)
 	}
 	return stats, err
 }
diff --git a/internal/utils/pgxv5/rows.go b/internal/utils/pgxv5/rows.go
index 6f1daacd..25021376 100644
--- a/internal/utils/pgxv5/rows.go
+++ b/internal/utils/pgxv5/rows.go
@@ -2,14 +2,29 @@
 package pgxv5
 
 import (
-	"fmt"
 	"reflect"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgproto3/v2"
 	"github.com/jackc/pgx/v4"
 )
 
+func CollectStrings(rows pgx.Rows) ([]string, error) {
+	result := []string{}
+	for rows.Next() {
+		var version string
+		if err := rows.Scan(&version); err != nil {
+			return nil, errors.Errorf("failed to scan rows: %w", err)
+		}
+		result = append(result, version)
+	}
+	if err := rows.Err(); err != nil {
+		return nil, errors.Errorf("failed to parse rows: %w", err)
+	}
+	return result, nil
+}
+
 // CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T.
 func CollectRows[T any](rows pgx.Rows) ([]T, error) {
 	defer rows.Close()
@@ -18,18 +33,14 @@ func CollectRows[T any](rows pgx.Rows) ([]T, error) {
 
 	for rows.Next() {
 		var value T
-		err := ScanRowToStruct(rows, &value)
-		if err != nil {
-			return nil, err
-		}
-		if err != nil {
+		if err := ScanRowToStruct(rows, &value); err != nil {
 			return nil, err
 		}
 		slice = append(slice, value)
 	}
 
 	if err := rows.Err(); err != nil {
-		return nil, err
+		return nil, errors.Errorf("failed to collect rows: %w", err)
 	}
 
 	return slice, nil
@@ -38,23 +49,25 @@ func CollectRows[T any](rows pgx.Rows) ([]T, error) {
 func ScanRowToStruct(rows pgx.Rows, dst any) error {
 	dstValue := reflect.ValueOf(dst)
 	if dstValue.Kind() != reflect.Ptr {
-		return fmt.Errorf("dst not a pointer")
+		return errors.Errorf("dst not a pointer")
 	}
 
 	dstElemValue := dstValue.Elem()
 	scanTargets, err := appendScanTargets(dstElemValue, nil, rows.FieldDescriptions())
-
 	if err != nil {
 		return err
 	}
 
 	for i, t := range scanTargets {
 		if t == nil {
-			return fmt.Errorf("struct doesn't have corresponding row field %s", rows.FieldDescriptions()[i].Name)
+			return errors.Errorf("struct doesn't have corresponding row field %s", rows.FieldDescriptions()[i].Name)
 		}
 	}
 
-	return rows.Scan(scanTargets...)
+	if err := rows.Scan(scanTargets...); err != nil {
+		return errors.Errorf("failed to scan targets: %w", err)
+	}
+	return nil
 }
 
 const structTagKey = "db"
@@ -104,7 +117,7 @@ func appendScanTargets(dstElemValue reflect.Value, scanTargets []any, fldDescs [
 			}
 			fpos := fieldPosByName(fldDescs, colName)
 			if fpos == -1 || fpos >= len(scanTargets) {
-				return nil, fmt.Errorf("cannot find field %s in returned row", colName)
+				return nil, errors.Errorf("cannot find field %s in returned row", colName)
 			}
 			scanTargets[fpos] = dstElemValue.Field(i).Addr().Interface()
 		}
diff --git a/internal/utils/prompt.go b/internal/utils/prompt.go
index 9f4ff07b..c149f611 100644
--- a/internal/utils/prompt.go
+++ b/internal/utils/prompt.go
@@ -3,7 +3,6 @@ package utils
 import (
 	"bufio"
 	"context"
-	"errors"
 	"fmt"
 	"io"
 	"os"
@@ -12,6 +11,7 @@ import (
 	"github.com/charmbracelet/bubbles/list"
 	tea "github.com/charmbracelet/bubbletea"
 	"github.com/charmbracelet/lipgloss"
+	"github.com/go-errors/errors"
 	"golang.org/x/term"
 )
 
@@ -132,7 +132,7 @@ func PromptChoice(ctx context.Context, title string, items []PromptItem) (Prompt
 	prog := tea.NewProgram(initial)
 	state, err := prog.Run()
 	if err != nil {
-		return initial.choice, err
+		return initial.choice, errors.Errorf("failed to prompt choice: %w", err)
 	}
 	if ctx.Err() != nil {
 		return initial.choice, ctx.Err()
diff --git a/internal/utils/tenant/client.go b/internal/utils/tenant/client.go
index 0b7d2481..a9dd1aad 100644
--- a/internal/utils/tenant/client.go
+++ b/internal/utils/tenant/client.go
@@ -2,11 +2,10 @@ package tenant
 
 import (
 	"context"
-	"errors"
-	"fmt"
 	"net/http"
 	"sync"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
@@ -32,11 +31,11 @@ func GetApiKeys(ctx context.Context, projectRef string) (ApiKey, error) {
 	keyOnce.Do(func() {
 		resp, err := utils.GetSupabase().GetProjectApiKeysWithResponse(ctx, projectRef)
 		if err != nil {
-			errKey = err
+			errKey = errors.Errorf("failed to get api keys: %w", err)
 			return
 		}
 		if resp.JSON200 == nil {
-			errKey = fmt.Errorf("%w: %s", ErrAuthToken, string(resp.Body))
+			errKey = errors.Errorf("%w: %s", ErrAuthToken, string(resp.Body))
 			return
 		}
 		for _, key := range *resp.JSON200 {
@@ -48,7 +47,7 @@ func GetApiKeys(ctx context.Context, projectRef string) (ApiKey, error) {
 			}
 		}
 		if apiKey.IsEmpty() {
-			errKey = errMissingKey
+			errKey = errors.New(errMissingKey)
 		}
 	})
 	return apiKey, errKey
diff --git a/internal/utils/tenant/database.go b/internal/utils/tenant/database.go
new file mode 100644
index 00000000..6978440b
--- /dev/null
+++ b/internal/utils/tenant/database.go
@@ -0,0 +1,26 @@
+package tenant
+
+import (
+	"context"
+
+	"github.com/go-errors/errors"
+	"github.com/supabase/cli/internal/utils"
+)
+
+var errDatabaseVersion = errors.New("Database version not found.")
+
+func GetDatabaseVersion(ctx context.Context, projectRef string) (string, error) {
+	resp, err := utils.GetSupabase().GetProjectsWithResponse(ctx)
+	if err != nil {
+		return "", errors.Errorf("failed to retrieve projects: %w", err)
+	}
+	if resp.JSON200 == nil {
+		return "", errors.New("Unexpected error retrieving projects: " + string(resp.Body))
+	}
+	for _, project := range *resp.JSON200 {
+		if project.Id == projectRef && len(project.Database.Version) > 0 {
+			return project.Database.Version, nil
+		}
+	}
+	return "", errors.New(errDatabaseVersion)
+}
diff --git a/internal/utils/tenant/gotrue.go b/internal/utils/tenant/gotrue.go
index 7eedadbe..8ff9a779 100644
--- a/internal/utils/tenant/gotrue.go
+++ b/internal/utils/tenant/gotrue.go
@@ -2,9 +2,9 @@ package tenant
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
@@ -27,7 +27,7 @@ func GetGotrueVersion(ctx context.Context, projectRef string) (string, error) {
 		return "", err
 	}
 	if len(data.Version) == 0 {
-		return "", errGotrueVersion
+		return "", errors.New(errGotrueVersion)
 	}
 	return data.Version, nil
 }
diff --git a/internal/utils/tenant/postgrest.go b/internal/utils/tenant/postgrest.go
index 68f7c259..d0d7020b 100644
--- a/internal/utils/tenant/postgrest.go
+++ b/internal/utils/tenant/postgrest.go
@@ -2,10 +2,10 @@ package tenant
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
@@ -33,7 +33,7 @@ func GetPostgrestVersion(ctx context.Context, projectRef string) (string, error)
 		return "", err
 	}
 	if len(data.Info.Version) == 0 {
-		return "", errPostgrestVersion
+		return "", errors.New(errPostgrestVersion)
 	}
 	parts := strings.Split(data.Info.Version, " ")
 	return "v" + parts[0], nil
diff --git a/internal/utils/tenant/storage.go b/internal/utils/tenant/storage.go
index e406f95e..7022b83f 100644
--- a/internal/utils/tenant/storage.go
+++ b/internal/utils/tenant/storage.go
@@ -2,9 +2,9 @@ package tenant
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/supabase/cli/internal/utils"
 )
 
@@ -21,7 +21,7 @@ func GetStorageVersion(ctx context.Context, projectRef string) (string, error) {
 		return "", err
 	}
 	if len(data) == 0 || data == "0.0.0" {
-		return "", errStorageVersion
+		return "", errors.New(errStorageVersion)
 	}
 	return "v" + data, nil
 }
diff --git a/internal/vanity_subdomains/activate/activate.go b/internal/vanity_subdomains/activate/activate.go
index f814fba2..4c954f6e 100644
--- a/internal/vanity_subdomains/activate/activate.go
+++ b/internal/vanity_subdomains/activate/activate.go
@@ -2,10 +2,10 @@ package activate
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -26,7 +26,7 @@ func Run(ctx context.Context, projectRef string, desiredSubdomain string, fsys a
 			VanitySubdomain: subdomain,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed activate vanity subdomain: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to create vanity subdomain config: " + string(resp.Body))
diff --git a/internal/vanity_subdomains/check/check.go b/internal/vanity_subdomains/check/check.go
index a58a8f70..26da5bfe 100644
--- a/internal/vanity_subdomains/check/check.go
+++ b/internal/vanity_subdomains/check/check.go
@@ -2,10 +2,10 @@ package check
 
 import (
 	"context"
-	"errors"
 	"fmt"
 	"strings"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 	"github.com/supabase/cli/pkg/api"
@@ -26,7 +26,7 @@ func Run(ctx context.Context, projectRef string, desiredSubdomain string, fsys a
 			VanitySubdomain: subdomain,
 		})
 		if err != nil {
-			return err
+			return errors.Errorf("failed to check vanity subdomain: %w", err)
 		}
 		if resp.JSON201 == nil {
 			return errors.New("failed to check subdomain availability: " + string(resp.Body))
diff --git a/internal/vanity_subdomains/delete/delete.go b/internal/vanity_subdomains/delete/delete.go
index 6c4da5b0..2b45f8c9 100644
--- a/internal/vanity_subdomains/delete/delete.go
+++ b/internal/vanity_subdomains/delete/delete.go
@@ -2,9 +2,9 @@ package delete
 
 import (
 	"context"
-	"errors"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -15,7 +15,7 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		resp, err := utils.GetSupabase().RemoveVanitySubdomainConfigWithResponse(ctx, projectRef)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to delete vanity subdomain: %w", err)
 		}
 		if resp.StatusCode() != 200 {
 			return errors.New("failed to delete vanity subdomain config; received: " + string(resp.Body))
diff --git a/internal/vanity_subdomains/get/get.go b/internal/vanity_subdomains/get/get.go
index b0560dc9..27ac0ef3 100644
--- a/internal/vanity_subdomains/get/get.go
+++ b/internal/vanity_subdomains/get/get.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -14,10 +15,10 @@ func Run(ctx context.Context, projectRef string, fsys afero.Fs) error {
 	{
 		response, err := utils.GetSupabase().GetVanitySubdomainConfigWithResponse(ctx, projectRef)
 		if err != nil {
-			return err
+			return errors.Errorf("failed to get vanity subdomain: %w", err)
 		}
 		if response.JSON200 == nil {
-			return fmt.Errorf("failed to obtain vanity subdomain config: %+v", string(response.Body))
+			return errors.Errorf("failed to obtain vanity subdomain config: %+v", string(response.Body))
 		}
 		fmt.Printf("Status: %s\n", response.JSON200.Status)
 		if response.JSON200.CustomDomain != nil {
diff --git a/tools/publish/main.go b/tools/publish/main.go
index 05a6a555..e9202eae 100644
--- a/tools/publish/main.go
+++ b/tools/publish/main.go
@@ -15,6 +15,7 @@ import (
 	"strings"
 	"text/template"
 
+	"github.com/go-errors/errors"
 	"github.com/google/go-github/v53/github"
 	"github.com/supabase/cli/tools/shared"
 )
@@ -99,9 +100,9 @@ func checkStatus(resp *http.Response, status int) error {
 	}
 	data, err := io.ReadAll(resp.Body)
 	if err != nil {
-		return fmt.Errorf("status %d: %w", resp.StatusCode, err)
+		return errors.Errorf("status %d: %w", resp.StatusCode, err)
 	}
-	return fmt.Errorf("status %d: %s", resp.StatusCode, string(data))
+	return errors.Errorf("status %d: %s", resp.StatusCode, string(data))
 }
 
 func updatePackage(ctx context.Context, client *github.Client, repo, path string, tmpl *template.Template, config PackageConfig) error {


Test patch:
diff --git a/internal/branches/create/create_test.go b/internal/branches/create/create_test.go
new file mode 100644
index 00000000..3c619435
--- /dev/null
+++ b/internal/branches/create/create_test.go
@@ -0,0 +1,84 @@
+package create
+
+import (
+	"context"
+	"net"
+	"net/http"
+	"os"
+	"testing"
+
+	"github.com/spf13/afero"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"github.com/supabase/cli/internal/testing/apitest"
+	"github.com/supabase/cli/internal/testing/fstest"
+	"github.com/supabase/cli/internal/utils"
+	"github.com/supabase/cli/pkg/api"
+	"gopkg.in/h2non/gock.v1"
+)
+
+func TestCreateCommand(t *testing.T) {
+	t.Run("creates preview branch", func(t *testing.T) {
+		// Setup valid project ref
+		ref := apitest.RandomProjectRef()
+		// Setup valid access token
+		token := apitest.RandomAccessToken(t)
+		t.Setenv("SUPABASE_ACCESS_TOKEN", string(token))
+		// Setup in-memory fs
+		fsys := afero.NewMemMapFs()
+		require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
+		// Setup mock api
+		defer gock.OffAll()
+		gock.New(utils.DefaultApiHost).
+			Post("/v1/projects/" + ref + "/branches").
+			Reply(http.StatusCreated).
+			JSON(api.BranchResponse{
+				Id: "test-uuid",
+			})
+		// Run test
+		err := Run(context.Background(), "", "sin", fsys)
+		// Check error
+		assert.NoError(t, err)
+	})
+
+	t.Run("throws error on permission denied", func(t *testing.T) {
+		// Setup in-memory fs
+		fsys := &fstest.OpenErrorFs{DenyPath: utils.ProjectRefPath}
+		// Run test
+		err := Run(context.Background(), "branch", "region", fsys)
+		// Check error
+		assert.ErrorIs(t, err, os.ErrPermission)
+	})
+
+	t.Run("throws error on network disconnected", func(t *testing.T) {
+		ref := apitest.RandomProjectRef()
+		// Setup in-memory fs
+		fsys := afero.NewMemMapFs()
+		require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
+		// Setup mock api
+		defer gock.OffAll()
+		gock.New(utils.DefaultApiHost).
+			Post("/v1/projects/" + ref + "/branches").
+			ReplyError(net.ErrClosed)
+		// Run test
+		err := Run(context.Background(), "", "sin", fsys)
+		// Check error
+		assert.ErrorIs(t, err, net.ErrClosed)
+	})
+
+	t.Run("throws error on service unavailable", func(t *testing.T) {
+		ref := apitest.RandomProjectRef()
+		// Setup in-memory fs
+		fsys := afero.NewMemMapFs()
+		require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
+		// Setup mock api
+		defer gock.OffAll()
+		gock.New(utils.DefaultApiHost).
+			Post("/v1/projects/" + ref + "/branches").
+			Reply(http.StatusServiceUnavailable)
+		// Run test
+		err := Run(context.Background(), "", "sin", fsys)
+		// Check error
+		assert.ErrorContains(t, err, "Unexpected error creating preview branch:")
+	})
+}
diff --git a/internal/db/branch/switch_/switch__test.go b/internal/db/branch/switch_/switch__test.go
index 283477a9..a5a86761 100644
--- a/internal/db/branch/switch_/switch__test.go
+++ b/internal/db/branch/switch_/switch__test.go
@@ -175,7 +175,7 @@ func TestSwitchCommand(t *testing.T) {
 		// Run test
 		err := Run(context.Background(), branch, fsys, conn.Intercept)
 		// Check error
-		assert.ErrorContains(t, err, "Error switching to branch target: conn closed")
+		assert.ErrorContains(t, err, "Error switching to branch target")
 		assert.Empty(t, apitest.ListUnmatchedRequests())
 	})
 
diff --git a/internal/db/reset/reset_test.go b/internal/db/reset/reset_test.go
index d707e49d..b65210ab 100644
--- a/internal/db/reset/reset_test.go
+++ b/internal/db/reset/reset_test.go
@@ -12,7 +12,6 @@ import (
 	"time"
 
 	"github.com/docker/docker/api/types"
-	"github.com/docker/docker/errdefs"
 	"github.com/jackc/pgconn"
 	"github.com/jackc/pgerrcode"
 	"github.com/spf13/afero"
@@ -276,7 +275,7 @@ func TestRestartDatabase(t *testing.T) {
 		// Run test
 		err := RestartDatabase(context.Background(), io.Discard)
 		// Check error
-		assert.True(t, errdefs.IsUnavailable(err))
+		assert.ErrorContains(t, err, "failed to restart container")
 		assert.Empty(t, apitest.ListUnmatchedRequests())
 	})
 
diff --git a/internal/db/test/test.go b/internal/db/test/test.go
index a1e083f6..8afd1aee 100644
--- a/internal/db/test/test.go
+++ b/internal/db/test/test.go
@@ -10,6 +10,7 @@ import (
 	"path/filepath"
 
 	"github.com/docker/docker/api/types"
+	"github.com/go-errors/errors"
 	"github.com/spf13/afero"
 	"github.com/supabase/cli/internal/utils"
 )
@@ -38,10 +39,10 @@ func pgProve(ctx context.Context, dstPath string, fsys afero.Fs) error {
 	// Copy tests into database container
 	var buf bytes.Buffer
 	if err := compress(utils.DbTestsDir, &buf, fsys); err != nil {
-		return err
+		return errors.Errorf("failed to compress directory: %w", err)
 	}
 	if err := utils.Docker.CopyToContainer(ctx, utils.DbId, dstPath, &buf, types.CopyToContainerOptions{}); err != nil {
-		return err
+		return errors.Errorf("failed to copy into container: %w", err)
 	}
 	// Passing in script string means command line args must be set manually, ie. "$@"
 	args := "set -- " + filepath.ToSlash(utils.DbTestsDir) + ";"
diff --git a/internal/functions/new/new_test.go b/internal/functions/new/new_test.go
index 69b303b4..956a1fa3 100644
--- a/internal/functions/new/new_test.go
+++ b/internal/functions/new/new_test.go
@@ -33,8 +33,8 @@ func TestNewCommand(t *testing.T) {
 	t.Run("throws error on duplicate slug", func(t *testing.T) {
 		// Setup in-memory fs
 		fsys := afero.NewMemMapFs()
-		funcDir := filepath.Join(utils.FunctionsDir, "test-func")
-		require.NoError(t, fsys.Mkdir(funcDir, 0755))
+		funcPath := filepath.Join(utils.FunctionsDir, "test-func", "index.ts")
+		require.NoError(t, afero.WriteFile(fsys, funcPath, []byte{}, 0644))
 		// Run test
 		assert.Error(t, Run(context.Background(), "test-func", fsys))
 	})
diff --git a/internal/migration/list/list_test.go b/internal/migration/list/list_test.go
index 4eccb780..c8f0cfc9 100644
--- a/internal/migration/list/list_test.go
+++ b/internal/migration/list/list_test.go
@@ -93,7 +93,7 @@ func TestRemoteMigrations(t *testing.T) {
 		// Run test
 		versions, err := loadRemoteVersions(context.Background(), dbConfig, conn.Intercept)
 		// Check error
-		assert.NoError(t, err)
+		assert.ErrorContains(t, err, "failed to parse rows")
 		assert.Empty(t, versions)
 	})
 
diff --git a/internal/migration/repair/repair_test.go b/internal/migration/repair/repair_test.go
index 220e8e4f..61bac80b 100644
--- a/internal/migration/repair/repair_test.go
+++ b/internal/migration/repair/repair_test.go
@@ -133,7 +133,7 @@ func TestMigrationFile(t *testing.T) {
 		migration, err := NewMigrationFromReader(strings.NewReader(sql))
 		// Check error
 		assert.ErrorIs(t, err, bufio.ErrTooLong)
-		assert.ErrorContains(t, err, "After statement 1:     BEGIN;")
+		assert.ErrorContains(t, err, "After statement 1: \tBEGIN;")
 		assert.Nil(t, migration)
 	})
 
diff --git a/internal/sso/internal/saml/files_test.go b/internal/sso/internal/saml/files_test.go
index 6791504a..ec7afe6d 100644
--- a/internal/sso/internal/saml/files_test.go
+++ b/internal/sso/internal/saml/files_test.go
@@ -7,65 +7,47 @@ import (
 
 	"github.com/spf13/afero"
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 )
 
 func TestReadAttributeMappingFile(t *testing.T) {
 	t.Run("open file that does not exist", func(t *testing.T) {
 		_, err := ReadAttributeMappingFile(afero.NewMemMapFs(), "/does-not-exist")
-		if !os.IsNotExist(err) {
-			t.Fatalf("unexpected error %v", err)
-		}
+		assert.ErrorIs(t, err, os.ErrNotExist)
 	})
 
 	t.Run("open file that is not valid JSON", func(t *testing.T) {
 		fs := afero.NewMemMapFs()
-		assert.NoError(t, afero.WriteFile(fs, "/not-valid-json", []byte("not-valid-JSON"), 0755))
+		require.NoError(t, afero.WriteFile(fs, "/not-valid-json", []byte("not-valid-JSON"), 0755))
 
 		_, err := ReadAttributeMappingFile(fs, "/not-valid-json")
-		if err == nil {
-			t.Fatalf("expected error")
-		}
+		assert.ErrorContains(t, err, "failed to parse attribute mapping")
 	})
 
 	t.Run("open valid file", func(t *testing.T) {
 		fs := afero.NewMemMapFs()
-		assert.NoError(t, afero.WriteFile(fs, "/valid-json", []byte(`{"keys":{"abc":{"names":["x","y","z"],"default":2,"name":"k"}}}`), 0755))
+		require.NoError(t, afero.WriteFile(fs, "/valid-json", []byte(`{"keys":{"abc":{"names":["x","y","z"],"default":2,"name":"k"}}}`), 0755))
 
 		_, err := ReadAttributeMappingFile(fs, "/valid-json")
-		if err != nil {
-			t.Fatalf("unexpected error %v", err)
-		}
+		assert.NoError(t, err)
 	})
 }
 
 func TestValidateMetadata(t *testing.T) {
 	t.Run("with invalid UTF-8", func(t *testing.T) {
 		err := ValidateMetadata([]byte{0xFF, 0xFF, 0xFF}, "/invalid-utf-8")
-		if err == nil || err.Error() != "SAML Metadata XML at \"/invalid-utf-8\" is not UTF-8 encoded" {
-			t.Fatalf("unexpected error %v", err)
-		}
+		assert.ErrorContains(t, err, `SAML Metadata XML at "/invalid-utf-8" is not UTF-8 encoded`)
 	})
 }
 
 func TestValidateMetadataURL(t *testing.T) {
 	t.Run("with relative URL", func(t *testing.T) {
 		err := ValidateMetadataURL(context.TODO(), "./relative-url")
-		if err == nil || err.Error() != "parse \"./relative-url\": invalid URI for request" {
-			t.Fatalf("unexpected error %v", err)
-		}
+		assert.ErrorContains(t, err, "invalid URI for request")
 	})
 
 	t.Run("with HTTP URL", func(t *testing.T) {
 		err := ValidateMetadataURL(context.TODO(), "http://example.com")
-		if err == nil || err.Error() != "only HTTPS Metadata URLs are supported" {
-			t.Fatalf("unexpected error %v", err)
-		}
-	})
-
-	t.Run("with HTTP URL", func(t *testing.T) {
-		err := ValidateMetadataURL(context.TODO(), "http://example.com")
-		if err == nil || err.Error() != "only HTTPS Metadata URLs are supported" {
-			t.Fatalf("unexpected error %v", err)
-		}
+		assert.ErrorContains(t, err, "only HTTPS Metadata URLs are supported")
 	})
 }
diff --git a/internal/test/new/new.go b/internal/test/new/new.go
index 3fb61345..a8bf177f 100644
--- a/internal/test/new/new.go
+++ b/internal/test/new/new.go
@@ -22,17 +22,14 @@ var (
 
 func Run(ctx context.Context, name, template string, fsys afero.Fs) error {
 	path := filepath.Join(utils.DbTestsDir, fmt.Sprintf("%s_test.sql", name))
-	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(path)); err != nil {
-		return err
-	}
 	if _, err := fsys.Stat(path); err == nil {
 		return errors.New(path + " already exists.")
 	}
-	err := afero.WriteFile(fsys, path, getTemplate(template), 0644)
-	if err == nil {
-		fmt.Printf("Created new %s test at %s.\n", template, utils.Bold(path))
+	if err := utils.WriteFile(path, getTemplate(template), fsys); err != nil {
+		return err
 	}
-	return err
+	fmt.Printf("Created new %s test at %s.\n", template, utils.Bold(path))
+	return nil
 }
 
 func getTemplate(name string) []byte {
diff --git a/internal/testing/pgtest/step.go b/internal/testing/pgtest/step.go
index 2dd37a2e..9dd7fd39 100644
--- a/internal/testing/pgtest/step.go
+++ b/internal/testing/pgtest/step.go
@@ -1,9 +1,9 @@
 package pgtest
 
 import (
-	"fmt"
 	"reflect"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgmock"
 	"github.com/jackc/pgproto3/v2"
 	"github.com/jackc/pgtype"
@@ -26,7 +26,7 @@ func (e *extendedQueryStep) Step(backend *pgproto3.Backend) error {
 	if m, ok := msg.(*pgproto3.Parse); ok {
 		want := &pgproto3.Parse{Name: m.Name, Query: e.sql, ParameterOIDs: m.ParameterOIDs}
 		if !reflect.DeepEqual(m, want) {
-			return fmt.Errorf("msg => %#v, e.want => %#v", m, want)
+			return errors.Errorf("msg => %#v, e.want => %#v", m, want)
 		}
 		// Anonymous ps falls through
 		if m.Name != "" {
@@ -62,7 +62,7 @@ func (e *extendedQueryStep) Step(backend *pgproto3.Backend) error {
 			PreparedStatement:    m.PreparedStatement,
 		}
 		if !reflect.DeepEqual(m, want) {
-			return fmt.Errorf("msg => %#v, e.want => %#v", msg, want)
+			return errors.Errorf("msg => %#v, e.want => %#v", msg, want)
 		}
 		e.reply.Steps = append([]pgmock.Step{
 			pgmock.ExpectMessage(&pgproto3.Describe{ObjectType: 'P'}),
@@ -80,7 +80,7 @@ func (e *extendedQueryStep) Step(backend *pgproto3.Backend) error {
 		return e.reply.Run(backend)
 	}
 
-	return fmt.Errorf("msg => %#v, e.want => %#v", msg, want)
+	return errors.Errorf("msg => %#v, e.want => %#v", msg, want)
 }
 
 // Expects a SQL query in any form: simple, prepared, or anonymous.
@@ -101,7 +101,7 @@ func (e *terminateStep) Step(backend *pgproto3.Backend) error {
 		return nil
 	}
 
-	return fmt.Errorf("msg => %#v, e.want => %#v", msg, &pgproto3.Terminate{})
+	return errors.Errorf("msg => %#v, e.want => %#v", msg, &pgproto3.Terminate{})
 }
 
 func ExpectTerminate() pgmock.Step {
diff --git a/internal/utils/connect_test.go b/internal/utils/connect_test.go
index a154d6b3..9709b3f1 100644
--- a/internal/utils/connect_test.go
+++ b/internal/utils/connect_test.go
@@ -2,9 +2,11 @@ package utils
 
 import (
 	"context"
+	"net"
 	"net/http"
 	"testing"
 
+	"github.com/go-errors/errors"
 	"github.com/jackc/pgconn"
 	"github.com/spf13/viper"
 	"github.com/stretchr/testify/assert"
@@ -23,7 +25,27 @@ var dbConfig = pgconn.Config{
 }
 
 func TestConnectRemotePostgres(t *testing.T) {
-	t.Run("connects to remote postgres successfully", func(t *testing.T) {
+	t.Run("connects to remote postgres with DoH", func(t *testing.T) {
+		DNSResolver.Value = DNS_OVER_HTTPS
+		// Setup http mock
+		defer gock.OffAll()
+		// pgx makes 2 calls to resolve ip for each connect request
+		gock.New("https://1.1.1.1").
+			Get("/dns-query").
+			MatchParam("name", dbConfig.Host).
+			MatchHeader("accept", "application/dns-json").
+			Reply(http.StatusOK).
+			JSON(&dnsResponse{Answer: []dnsAnswer{
+				{Type: dnsIPv4Type, Data: "127.0.0.1"},
+			}})
+		gock.New("https://1.1.1.1").
+			Get("/dns-query").
+			MatchParam("name", dbConfig.Host).
+			MatchHeader("accept", "application/dns-json").
+			Reply(http.StatusOK).
+			JSON(&dnsResponse{Answer: []dnsAnswer{
+				{Type: dnsIPv4Type, Data: "127.0.0.1"},
+			}})
 		// Setup mock postgres
 		conn := pgtest.NewConn()
 		defer conn.Close(t)
@@ -34,7 +56,8 @@ func TestConnectRemotePostgres(t *testing.T) {
 		assert.NoError(t, err)
 	})
 
-	t.Run("preserves db password", func(t *testing.T) {
+	t.Run("connects with unescaped db password", func(t *testing.T) {
+		DNSResolver.Value = DNS_GO_NATIVE
 		// Setup mock postgres
 		conn := pgtest.NewConn()
 		defer conn.Close(t)
@@ -47,51 +70,46 @@ func TestConnectRemotePostgres(t *testing.T) {
 		assert.Equal(t, config.Password, c.Config().Password)
 	})
 
-	t.Run("fallback to postgres port on timeout", func(t *testing.T) {
+	t.Run("abort on dial error when connecting directly", func(t *testing.T) {
 		DNSResolver.Value = DNS_OVER_HTTPS
+		netErr := errors.New("network error")
 		// Setup http mock
 		defer gock.OffAll()
 		gock.New("https://1.1.1.1").
 			Get("/dns-query").
-			MatchParam("name", dbConfig.Host).
-			MatchHeader("accept", "application/dns-json").
-			Reply(http.StatusOK).
-			JSON(&dnsResponse{Answer: []dnsAnswer{
-				{Type: dnsIPv4Type, Data: "127.0.0.1"},
-			}})
-		gock.New("https://1.1.1.1").
-			Get("/dns-query").
-			MatchParam("name", dbConfig.Host).
+			MatchParam("name", "fly.dev").
 			MatchHeader("accept", "application/dns-json").
-			Reply(http.StatusOK).
-			JSON(&dnsResponse{Answer: []dnsAnswer{
-				{Type: dnsIPv4Type, Data: "127.0.0.1"},
-			}})
-		// pgx makes 2 calls to resolve ip for each connect request
+			ReplyError(&net.OpError{Op: "dial", Err: netErr})
+		// Run test
+		_, err := ConnectRemotePostgres(context.Background(), pgconn.Config{
+			Host: "fly.dev",
+			Port: 6543,
+		})
+		// Check error
+		require.ErrorIs(t, err, netErr)
+		assert.Empty(t, apitest.ListUnmatchedRequests())
+	})
+
+	t.Run("fallback to postgres port on dial error", func(t *testing.T) {
+		DNSResolver.Value = DNS_OVER_HTTPS
+		netErr := errors.New("network error")
+		// Setup http mock
+		defer gock.OffAll()
 		gock.New("https://1.1.1.1").
 			Get("/dns-query").
 			MatchParam("name", dbConfig.Host).
 			MatchHeader("accept", "application/dns-json").
-			Reply(http.StatusOK).
-			JSON(&dnsResponse{Answer: []dnsAnswer{
-				{Type: dnsIPv4Type, Data: "127.0.0.1"},
-			}})
+			ReplyError(&net.OpError{Op: "dial", Err: netErr})
 		gock.New("https://1.1.1.1").
 			Get("/dns-query").
 			MatchParam("name", dbConfig.Host).
 			MatchHeader("accept", "application/dns-json").
-			Reply(http.StatusOK).
-			JSON(&dnsResponse{Answer: []dnsAnswer{
-				{Type: dnsIPv4Type, Data: "127.0.0.1"},
-			}})
-		// Setup mock postgres
-		conn := pgtest.NewConn()
-		defer conn.Close(t)
+			ReplyError(&net.OpError{Op: "dial", Err: netErr})
 		// Run test
-		c, err := ConnectRemotePostgres(context.Background(), dbConfig, conn.Intercept)
+		ctx := context.Background()
+		_, err := ConnectRemotePostgres(ctx, dbConfig)
 		// Check error
-		require.NoError(t, err)
-		defer c.Close(context.Background())
+		require.ErrorIs(t, err, netErr)
 		assert.Empty(t, apitest.ListUnmatchedRequests())
 	})
 }
@@ -99,7 +117,13 @@ func TestConnectRemotePostgres(t *testing.T) {
 func TestConnectLocal(t *testing.T) {
 	t.Run("connects with debug log", func(t *testing.T) {
 		viper.Set("DEBUG", true)
-		_, err := ConnectLocalPostgres(context.Background(), pgconn.Config{Host: "0"})
-		assert.Error(t, err)
+		_, err := ConnectLocalPostgres(context.Background(), pgconn.Config{Host: "0", Port: 6543})
+		assert.ErrorContains(t, err, "failed to connect to postgres")
+	})
+
+	t.Run("throws error on invalid port", func(t *testing.T) {
+		Config.Db.Port = 0
+		_, err := ConnectLocalPostgres(context.Background(), pgconn.Config{})
+		assert.ErrorContains(t, err, "invalid port (outside range)")
 	})
 }
diff --git a/internal/utils/parser/token_test.go b/internal/utils/parser/token_test.go
index 52afb269..566b1186 100644
--- a/internal/utils/parser/token_test.go
+++ b/internal/utils/parser/token_test.go
@@ -47,6 +47,6 @@ func TestSplitAndTrim(t *testing.T) {
 	stats, err := SplitAndTrim(strings.NewReader(sql))
 	// Check error
 	assert.ErrorIs(t, err, bufio.ErrTooLong)
-	assert.ErrorContains(t, err, "After statement 1:     BEGIN;")
+	assert.ErrorContains(t, err, "After statement 1: \tBEGIN;")
 	assert.ElementsMatch(t, []string{"BEGIN"}, stats)
 }