github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/util/error.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package util 21 22 import ( 23 "fmt" 24 "os" 25 "strings" 26 27 apierrors "k8s.io/apimachinery/pkg/api/errors" 28 utilerrors "k8s.io/apimachinery/pkg/util/errors" 29 cmdutil "k8s.io/kubectl/pkg/cmd/util" 30 ) 31 32 var ( 33 invalidAuthAPIVersion = "exec plugin: invalid apiVersion \"client.authentication.k8s.io/v1alpha1\"" 34 invalidAuthAPIVersionHint = "if you are using Amazon EKS, please update AWS CLI to the latest version and update the kubeconfig file for your cluster,\nrefer to https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html" 35 ) 36 37 // CheckErr prints a user-friendly error to STDERR and exits with a non-zero exit code. 38 func CheckErr(err error) { 39 // unwrap aggregates of 1 40 if agg, ok := err.(utilerrors.Aggregate); ok && len(agg.Errors()) == 1 { 41 err = agg.Errors()[0] 42 } 43 44 if err == nil { 45 return 46 } 47 48 // ErrExit and other valid api errors will be checked by cmdutil.CheckErr, now 49 // we only check invalid api errors that can not be converted to StatusError. 50 if err != cmdutil.ErrExit && apierrors.IsInvalid(err) { 51 if _, ok := err.(*apierrors.StatusError); !ok { 52 printErr(err) 53 os.Exit(cmdutil.DefaultErrorExitCode) 54 } 55 } 56 57 // check invalid authentication apiVersion and output hint message 58 if err.Error() == invalidAuthAPIVersion { 59 printErr(err) 60 fmt.Fprintf(os.Stderr, "hint: %s\n", invalidAuthAPIVersionHint) 61 os.Exit(cmdutil.DefaultErrorExitCode) 62 } 63 64 // check other errors 65 cmdutil.CheckErr(err) 66 } 67 68 func printErr(err error) { 69 msg, ok := cmdutil.StandardErrorMessage(err) 70 if !ok { 71 msg = err.Error() 72 if !strings.HasPrefix(msg, "error: ") { 73 msg = fmt.Sprintf("error: %s", msg) 74 } 75 } 76 if len(msg) > 0 { 77 // add newline if needed 78 if !strings.HasSuffix(msg, "\n") { 79 msg += "\n" 80 } 81 fmt.Fprint(os.Stderr, msg) 82 } 83 }