From b6628faadc2956f451c59694c15c6f2cde41269f Mon Sep 17 00:00:00 2001 From: r-vasquez Date: Mon, 25 Nov 2024 12:42:11 -0800 Subject: [PATCH] rpk: decode adminapi error message in role creation --- src/go/rpk/pkg/adminapi/admin.go | 16 ++++++++++++++++ src/go/rpk/pkg/cli/security/role/create.go | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/go/rpk/pkg/adminapi/admin.go b/src/go/rpk/pkg/adminapi/admin.go index 8c67799a932e..73d30c4850e2 100644 --- a/src/go/rpk/pkg/adminapi/admin.go +++ b/src/go/rpk/pkg/adminapi/admin.go @@ -131,6 +131,22 @@ func NewHostClient(fs afero.Fs, p *config.RpkProfile, host string) (*rpadmin.Adm return rpadmin.NewClient(addrs, tc, auth, p.FromCloud) } +// TryDecodeMessageFromErr tries to decode the message if it's a +// rpadmin.HTTPResponseError and logs the full error. Otherwise, it returns +// the original error string. +func TryDecodeMessageFromErr(err error) string { + if err == nil { + return "" + } + if he := (*rpadmin.HTTPResponseError)(nil); errors.As(err, &he) { + zap.L().Sugar().Debugf("got admin API error: %v", strings.TrimSpace(err.Error())) + if body, err := he.DecodeGenericErrorBody(); err == nil { + return body.Message + } + } + return strings.TrimSpace(err.Error()) +} + // licenseFeatureChecks checks if the user is talking to a cluster that has // enterprise features enabled without a license and returns a message with a // warning. diff --git a/src/go/rpk/pkg/cli/security/role/create.go b/src/go/rpk/pkg/cli/security/role/create.go index 339c29a8e001..1aa9c879c16e 100644 --- a/src/go/rpk/pkg/cli/security/role/create.go +++ b/src/go/rpk/pkg/cli/security/role/create.go @@ -46,7 +46,7 @@ flag in the 'rpk security acl create' command.`, roleName := args[0] _, err = cl.CreateRole(cmd.Context(), roleName) - out.MaybeDie(err, "unable to create role %q: %v", roleName, err) + out.MaybeDie(err, "unable to create role %q: %v", roleName, adminapi.TryDecodeMessageFromErr(err)) if isText, _, s, err := f.Format(createResponse{[]string{roleName}}); !isText { out.MaybeDie(err, "unable to print in the required format %q: %v", f.Kind, err)