github.com/haraldrudell/parl@v0.4.176/mains/minimal-recovery.go (about) 1 /* 2 © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package mains 7 8 import ( 9 "os" 10 "time" 11 12 "github.com/haraldrudell/parl" 13 "github.com/haraldrudell/parl/perrors" 14 ) 15 16 // MinimalRecovery handles error process exit for the main function 17 // - purpose is to avoid a silent zero status-code exit on error 18 // and to print exactly when the process exited 19 // - panics are not recovered 20 // - on success: *errp == nil: 21 // - – a timestamped success message is printed to stderr 22 // - — the function returns 23 // - on error: *errp != nil: 24 // - — if error is caused by panic, error is printed with stack trace 25 // - — other errors are printed as a one-liner with code-location 26 // - — os.Exit is invoked with status code 1 27 // 28 // Usage: 29 // 30 // main() { 31 // var err error 32 // defer mains.MinimalRecovery(&err) 33 func MinimalRecovery(errp *error) { 34 35 // process result 36 var err error 37 if errp != nil { 38 err = *errp 39 } 40 // process exit timestamp 41 var ts = time.Now().Format(parl.Rfc3339s) 42 43 // good exit: return 44 if err == nil { 45 parl.Log("%s Completed successfully", ts) 46 return // success return 47 } 48 49 // process exit with error 50 // - if panic: error with stack trace 51 // - other error: one-liner with code location 52 var eStr string 53 if isPanic, _, _, _ := perrors.IsPanic(err); isPanic { 54 eStr = perrors.Long(err) 55 } else { 56 eStr = perrors.Short(err) 57 } 58 parl.Log("%s error: %s", ts, eStr) 59 60 // exit code 1 61 os.Exit(1) 62 }