github.com/coveo/gotemplate@v2.7.7+incompatible/errors/errors.go (about) 1 package errors 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/fatih/color" 8 "github.com/go-errors/errors" 9 ) 10 11 // Raise issues a panic with a formated message representing a managed error 12 func Raise(format string, args ...interface{}) { 13 panic(Managed(fmt.Sprintf(format, args...))) 14 } 15 16 // Printf print a message to the stderr in red 17 func Printf(format string, args ...interface{}) { 18 Print(fmt.Errorf(format, args...)) 19 } 20 21 // Print print error to the stderr in red 22 func Print(err error) { 23 fmt.Fprintln(color.Error, color.RedString(fmt.Sprintf("%v", err))) 24 } 25 26 // Must traps errors and return the remaining results to the caller 27 // If there is an error, a panic is issued 28 func Must(result ...interface{}) interface{} { 29 if len(result) == 0 { 30 return nil 31 } 32 last := len(result) - 1 33 err := result[last] 34 35 if err != nil { 36 panic(errors.WrapPrefix(err, "errors.Must call failed", 2)) 37 } 38 39 result = result[:last] 40 switch len(result) { 41 case 0: 42 return nil 43 case 1: 44 return result[0] 45 default: 46 return result 47 } 48 } 49 50 // Trap catch any panic exception, and convert it to error 51 // It must be called with current error state and recover() as argument 52 func Trap(sourceErr error, recovered interface{}) (err error) { 53 err = sourceErr 54 var trap error 55 switch rec := recovered.(type) { 56 case nil: 57 case error: 58 trap = rec 59 default: 60 trap = fmt.Errorf("%v", rec) 61 } 62 if trap != nil { 63 if err != nil { 64 return Array{err, trap} 65 } 66 return trap 67 } 68 return 69 } 70 71 // TemplateNotFoundError is returned when a template does not exist 72 type TemplateNotFoundError struct { 73 name string 74 } 75 76 func (e TemplateNotFoundError) Error() string { 77 return fmt.Sprintf("Template %s not found", e.name) 78 } 79 80 // Array represent an array of error 81 type Array []error 82 83 func (errors Array) Error() string { 84 errorsStr := make([]string, 0, len(errors)) 85 for i := range errors { 86 if errors[i] != nil { 87 errorsStr = append(errorsStr, errors[i].Error()) 88 } 89 } 90 return strings.Join(errorsStr, "\n") 91 } 92 93 // Managed indicates an error that is properly handled (no need to print out stack) 94 type Managed string 95 96 func (err Managed) Error() string { 97 return string(err) 98 }