Improve code sequences with multiple errs

Signed-off-by: Paul Meyer <49727155+katexochen@users.noreply.github.com>
This commit is contained in:
Paul Meyer 2023-02-07 15:19:59 +01:00
parent 12c866bcb9
commit deea806d9c
9 changed files with 53 additions and 44 deletions

View File

@ -38,12 +38,10 @@ type rollbackerTerraform struct {
} }
func (r *rollbackerTerraform) rollback(ctx context.Context) error { func (r *rollbackerTerraform) rollback(ctx context.Context) error {
var err error if err := r.client.Destroy(ctx); err != nil {
err = errors.Join(err, r.client.Destroy(ctx)) return err
if err == nil {
err = errors.Join(err, r.client.CleanUpWorkspace())
} }
return err return r.client.CleanUpWorkspace()
} }
type rollbackerQEMU struct { type rollbackerQEMU struct {
@ -52,14 +50,12 @@ type rollbackerQEMU struct {
createdWorkspace bool createdWorkspace bool
} }
func (r *rollbackerQEMU) rollback(ctx context.Context) error { func (r *rollbackerQEMU) rollback(ctx context.Context) (retErr error) {
var err error
if r.createdWorkspace { if r.createdWorkspace {
err = errors.Join(err, r.client.Destroy(ctx)) retErr = r.client.Destroy(ctx)
} }
err = errors.Join(err, r.libvirt.Stop(ctx)) if retErr := errors.Join(retErr, r.libvirt.Stop(ctx)); retErr != nil {
if err == nil { return retErr
err = r.client.CleanUpWorkspace()
} }
return err return r.client.CleanUpWorkspace()
} }

View File

@ -76,14 +76,14 @@ func terminate(cmd *cobra.Command, terminator cloudTerminator, fileHandler file.
cmd.Println("Your Constellation cluster was terminated successfully.") cmd.Println("Your Constellation cluster was terminated successfully.")
var retErr error var removeErr error
if err := fileHandler.Remove(constants.AdminConfFilename); err != nil && !errors.Is(err, fs.ErrNotExist) { if err := fileHandler.Remove(constants.AdminConfFilename); err != nil && !errors.Is(err, fs.ErrNotExist) {
retErr = errors.Join(err, fmt.Errorf("failed to remove file: '%s', please remove it manually", constants.AdminConfFilename)) removeErr = errors.Join(err, fmt.Errorf("failed to remove file: '%s', please remove it manually", constants.AdminConfFilename))
} }
if err := fileHandler.Remove(constants.ClusterIDsFileName); err != nil && !errors.Is(err, fs.ErrNotExist) { if err := fileHandler.Remove(constants.ClusterIDsFileName); err != nil && !errors.Is(err, fs.ErrNotExist) {
retErr = errors.Join(err, fmt.Errorf("failed to remove file: '%s', please remove it manually", constants.ClusterIDsFileName)) removeErr = errors.Join(err, fmt.Errorf("failed to remove file: '%s', please remove it manually", constants.ClusterIDsFileName))
} }
return retErr return removeErr
} }

View File

@ -116,9 +116,7 @@ func (s *debugdServer) UploadFiles(stream pb.Debugd_UploadFilesServer) error {
} }
// continue on error to allow other units to be overridden // continue on error to allow other units to be overridden
err = s.serviceManager.OverrideServiceUnitExecStart(stream.Context(), file.OverrideServiceUnit, file.TargetPath) err = s.serviceManager.OverrideServiceUnitExecStart(stream.Context(), file.OverrideServiceUnit, file.TargetPath)
if err != nil { overrideUnitErr = errors.Join(overrideUnitErr, err)
overrideUnitErr = errors.Join(overrideUnitErr, err)
}
} }
if overrideUnitErr != nil { if overrideUnitErr != nil {

View File

@ -35,7 +35,7 @@ type libvirtInstance struct {
imagePath string imagePath string
} }
func (l *libvirtInstance) uploadBaseImage(baseVolume *libvirt.StorageVol) (err error) { func (l *libvirtInstance) uploadBaseImage(baseVolume *libvirt.StorageVol) (retErr error) {
stream, err := l.conn.NewStream(libvirt.STREAM_NONBLOCK) stream, err := l.conn.NewStream(libvirt.STREAM_NONBLOCK)
if err != nil { if err != nil {
return err return err
@ -46,7 +46,7 @@ func (l *libvirtInstance) uploadBaseImage(baseVolume *libvirt.StorageVol) (err e
return fmt.Errorf("error while opening %s: %s", l.imagePath, err) return fmt.Errorf("error while opening %s: %s", l.imagePath, err)
} }
defer func() { defer func() {
err = errors.Join(err, file.Close()) retErr = errors.Join(err, file.Close())
}() }()
fi, err := file.Stat() fi, err := file.Stat()
@ -282,7 +282,7 @@ func (l *libvirtInstance) deleteLibvirtInstance() error {
return err return err
} }
func (l *libvirtInstance) obtainMeasurements() (measurements measurements.M, err error) { func (l *libvirtInstance) obtainMeasurements() (measurements measurements.M, retErr error) {
// sanity check // sanity check
if err := l.deleteLibvirtInstance(); err != nil { if err := l.deleteLibvirtInstance(); err != nil {
return nil, err return nil, err
@ -295,7 +295,7 @@ func (l *libvirtInstance) obtainMeasurements() (measurements measurements.M, err
} }
}() }()
defer func() { defer func() {
err = errors.Join(err, l.deleteLibvirtInstance()) retErr = errors.Join(retErr, l.deleteLibvirtInstance())
}() }()
if err := l.createLibvirtInstance(); err != nil { if err := l.createLibvirtInstance(); err != nil {
return nil, err return nil, err

View File

@ -580,13 +580,13 @@ func (c *Config) Validate(force bool) error {
return nil return nil
} }
var errs validator.ValidationErrors var validationErrs validator.ValidationErrors
if !errors.As(err, &errs) { if !errors.As(err, &validationErrs) {
return err return err
} }
var validationErrMsgs []string var validationErrMsgs []string
for _, e := range errs { for _, e := range validationErrs {
validationErrMsgs = append(validationErrMsgs, e.Translate(trans)) validationErrMsgs = append(validationErrMsgs, e.Translate(trans))
} }

View File

@ -184,13 +184,19 @@ func TestNewWithDefaultOptions(t *testing.T) {
} }
func TestValidate(t *testing.T) { func TestValidate(t *testing.T) {
const defaultErrCount = 21 // expect this number of error messages by default because user-specific values are not set and multiple providers are defined by default
const azErrCount = 9
const gcpErrCount = 6
testCases := map[string]struct { testCases := map[string]struct {
cnf *Config cnf *Config
wantErr bool wantErr bool
wantErrCount int
}{ }{
"default config is not valid": { "default config is not valid": {
cnf: Default(), cnf: Default(),
wantErr: true, wantErr: true,
wantErrCount: defaultErrCount,
}, },
"v0 is one error": { "v0 is one error": {
cnf: func() *Config { cnf: func() *Config {
@ -198,7 +204,8 @@ func TestValidate(t *testing.T) {
cnf.Version = "v0" cnf.Version = "v0"
return cnf return cnf
}(), }(),
wantErr: true, wantErr: true,
wantErrCount: defaultErrCount + 1,
}, },
"v0 and negative state disk are two errors": { "v0 and negative state disk are two errors": {
cnf: func() *Config { cnf: func() *Config {
@ -207,7 +214,8 @@ func TestValidate(t *testing.T) {
cnf.StateDiskSizeGB = -1 cnf.StateDiskSizeGB = -1
return cnf return cnf
}(), }(),
wantErr: true, wantErr: true,
wantErrCount: defaultErrCount + 2,
}, },
"default Azure config is not valid": { "default Azure config is not valid": {
cnf: func() *Config { cnf: func() *Config {
@ -217,7 +225,8 @@ func TestValidate(t *testing.T) {
cnf.Provider.Azure = az cnf.Provider.Azure = az
return cnf return cnf
}(), }(),
wantErr: true, wantErr: true,
wantErrCount: azErrCount,
}, },
"Azure config with all required fields is valid": { "Azure config with all required fields is valid": {
cnf: func() *Config { cnf: func() *Config {
@ -245,7 +254,8 @@ func TestValidate(t *testing.T) {
cnf.Provider.GCP = gcp cnf.Provider.GCP = gcp
return cnf return cnf
}(), }(),
wantErr: true, wantErr: true,
wantErrCount: gcpErrCount,
}, },
"GCP config with all required fields is valid": { "GCP config with all required fields is valid": {
cnf: func() *Config { cnf: func() *Config {
@ -287,10 +297,15 @@ func TestValidate(t *testing.T) {
for name, tc := range testCases { for name, tc := range testCases {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
require := require.New(t)
err := tc.cnf.Validate(false) err := tc.cnf.Validate(false)
if tc.wantErr { if tc.wantErr {
assert.Error(err) assert.Error(err)
var valErr *ValidationError
require.ErrorAs(err, &valErr)
assert.Equal(tc.wantErrCount, valErr.messagesCount())
return return
} }
assert.NoError(err) assert.NoError(err)

View File

@ -47,6 +47,10 @@ func (e *ValidationError) LongMessage() string {
return msg return msg
} }
func (e *ValidationError) messagesCount() int {
return len(e.validationErrMsgs)
}
func registerInvalidK8sVersionError(ut ut.Translator) error { func registerInvalidK8sVersionError(ut ut.Translator) error {
return ut.Add("supported_k8s_version", "{0} specifies an unsupported Kubernetes version. {1}", true) return ut.Add("supported_k8s_version", "{0} specifies an unsupported Kubernetes version. {1}", true)
} }

View File

@ -735,14 +735,10 @@ func (w *tarGzWriter) Bytes() []byte {
return w.buf.Bytes() return w.buf.Bytes()
} }
func (w *tarGzWriter) Close() (result error) { func (w *tarGzWriter) Close() (retErr error) {
if err := w.tarWriter.Close(); err != nil { retErr = errors.Join(retErr, w.tarWriter.Close())
result = errors.Join(result, err) retErr = errors.Join(retErr, w.gzWriter.Close())
} return retErr
if err := w.gzWriter.Close(); err != nil {
result = errors.Join(result, err)
}
return result
} }
func stringPtr(s string) *string { func stringPtr(s string) *string {

View File

@ -152,8 +152,6 @@ func deleteSingleVersion(ctx context.Context, clients rmImageClients, ver versio
} }
func deleteRef(ctx context.Context, clients rmImageClients, ref string, dryrun bool, log *logger.Logger) error { func deleteRef(ctx context.Context, clients rmImageClients, ref string, dryrun bool, log *logger.Logger) error {
var retErr error
var vers []versionsapi.Version var vers []versionsapi.Version
for _, stream := range []string{"nightly", "console", "debug"} { for _, stream := range []string{"nightly", "console", "debug"} {
log.Infof("Listing versions of stream %s", stream) log.Infof("Listing versions of stream %s", stream)
@ -179,6 +177,8 @@ func deleteRef(ctx context.Context, clients rmImageClients, ref string, dryrun b
} }
log.Infof("Found %d versions to delete", len(vers)) log.Infof("Found %d versions to delete", len(vers))
var retErr error
for _, ver := range vers { for _, ver := range vers {
if err := deleteImage(ctx, clients, ver, dryrun, log); err != nil { if err := deleteImage(ctx, clients, ver, dryrun, log); err != nil {
retErr = errors.Join(retErr, fmt.Errorf("deleting images for version %s: %w", ver.Version, err)) retErr = errors.Join(retErr, fmt.Errorf("deleting images for version %s: %w", ver.Version, err))