github.com/elopio/cli@v6.21.2-0.20160902224010-ea909d1fdb2f+incompatible/utils/panichandler/handler.go (about)

     1  package panichandler
     2  
     3  import (
     4  	"html/template"
     5  	"os"
     6  	"runtime"
     7  	"strings"
     8  
     9  	"code.cloudfoundry.org/cli/cf"
    10  )
    11  
    12  //TODO: Burn this with fire
    13  const QuietPanic = "This shouldn't print anything"
    14  
    15  func HandlePanic() {
    16  	if err := recover(); err != nil {
    17  		if err != QuietPanic {
    18  			formattedString := `
    19  	Something unexpected happened. This is a bug in {{.Binary}}.
    20  
    21  	Please re-run the command that caused this exception with the environment
    22  	variable CF_TRACE set to true.
    23  
    24  	Also, please update to the latest cli and try the command again:
    25  	https://code.cloudfoundry.org/cli/releases
    26  
    27  	Please create an issue at: https://code.cloudfoundry.org/cli/issues
    28  
    29  	Include the below information when creating the issue:
    30  
    31  		Command
    32  		{{.Command}}
    33  
    34  		CLI Version
    35  		{{.Version}}
    36  
    37  		Error
    38  		{{.Error}}
    39  
    40  		Stack Trace
    41  {{.StackTrace}}
    42  
    43  		Your Platform Details
    44  		e.g. Mac OS X 10.11, Windows 8.1 64-bit, Ubuntu 14.04.3 64-bit
    45  
    46  		Shell
    47  		e.g. Terminal, iTerm, Powershell, Cygwin, gnome-terminal, terminator
    48  `
    49  			formattedTemplate := template.Must(template.New("Panic Template").Parse(formattedString))
    50  			formattedTemplate.Execute(os.Stderr, map[string]interface{}{
    51  				"Binary":     os.Args[0],
    52  				"Command":    strings.Join(os.Args, " "),
    53  				"Version":    cf.Version,
    54  				"StackTrace": generateBacktrace(),
    55  				"Error":      err,
    56  			})
    57  		}
    58  		os.Exit(1)
    59  	}
    60  }
    61  
    62  func generateBacktrace() string {
    63  	stackByteCount := 0
    64  	stackSizeLimit := 1024 * 1024
    65  	var bytes []byte
    66  	for stackSize := 1024; (stackByteCount == 0 || stackByteCount == stackSize) && stackSize < stackSizeLimit; stackSize = 2 * stackSize {
    67  		bytes = make([]byte, stackSize)
    68  		stackByteCount = runtime.Stack(bytes, true)
    69  	}
    70  	stackTrace := "\t" + strings.Replace(string(bytes), "\n", "\n\t", -1)
    71  	return stackTrace
    72  }