go.ligato.io/vpp-agent/v3@v3.5.0/cmd/agentctl/commands/errors.go (about) 1 // Copyright (c) 2019 Cisco and/or its affiliates. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at: 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package commands 16 17 import ( 18 "fmt" 19 "strings" 20 ) 21 22 // Errors is a list of errors. 23 // Useful in a loop if you don't want to return the error right away and you want to display after the loop, 24 // all the errors that happened during the loop. 25 type Errors []error 26 27 func (errList Errors) Error() string { 28 if len(errList) == 0 { 29 return "" 30 } 31 out := make([]string, len(errList)) 32 for i := range errList { 33 out[i] = errList[i].Error() 34 } 35 return strings.Join(out, ", ") 36 } 37 38 // StatusError reports an unsuccessful exit by a command. 39 type StatusError struct { 40 Status string 41 StatusCode int 42 } 43 44 func (e StatusError) String() string { 45 return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode) 46 } 47 48 func (e StatusError) Error() string { 49 return fmt.Sprintf("%s (%d)", e.Status, e.StatusCode) 50 } 51 52 // ExitCode returns proper exit code for err or 0 if err is nil. 53 func ExitCode(err error) int { 54 if err == nil { 55 return 0 56 } 57 if sterr, ok := err.(StatusError); ok { 58 // StatusError should only be used for errors, and all errors should 59 // have a non-zero exit status, so never exit with 0 60 if sterr.StatusCode != 0 { 61 return sterr.StatusCode 62 } 63 } 64 return 1 65 }