2022-05-18 11:03:40 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
2023-03-07 13:38:26 +00:00
|
|
|
sdkstatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
2022-05-18 11:03:40 +00:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ExitOnErr prints error and exits with a code that matches
|
|
|
|
// one of the common errors from sdk library. If no errors
|
|
|
|
// found, exits with 1 code.
|
|
|
|
// Does nothing if passed error in nil.
|
|
|
|
func ExitOnErr(cmd *cobra.Command, errFmt string, err error) {
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if errFmt != "" {
|
|
|
|
err = fmt.Errorf(errFmt, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
_ = iota
|
|
|
|
internal
|
|
|
|
aclDenied
|
2024-11-22 12:19:51 +00:00
|
|
|
apemanagerDenied
|
2022-05-18 11:03:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
code int
|
|
|
|
|
2024-11-22 12:19:51 +00:00
|
|
|
internalErr = new(sdkstatus.ServerInternal)
|
|
|
|
accessErr = new(sdkstatus.ObjectAccessDenied)
|
|
|
|
apemanagerErr = new(sdkstatus.APEManagerAccessDenied)
|
2022-05-18 11:03:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case errors.As(err, &internalErr):
|
|
|
|
code = internal
|
|
|
|
case errors.As(err, &accessErr):
|
|
|
|
code = aclDenied
|
|
|
|
err = fmt.Errorf("%w: %s", err, accessErr.Reason())
|
2024-11-22 12:19:51 +00:00
|
|
|
case errors.As(err, &apemanagerErr):
|
|
|
|
code = apemanagerDenied
|
|
|
|
err = fmt.Errorf("%w: %s", err, apemanagerErr.Reason())
|
2022-05-18 11:03:40 +00:00
|
|
|
default:
|
|
|
|
code = internal
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd.PrintErrln(err)
|
2023-06-05 15:54:59 +00:00
|
|
|
if cmd.PersistentPostRun != nil {
|
|
|
|
cmd.PersistentPostRun(cmd, nil)
|
|
|
|
}
|
2022-05-18 11:03:40 +00:00
|
|
|
os.Exit(code)
|
|
|
|
}
|