@kjk1/

gobook error handling errors in short programs

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.12324585979188951","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"Ly8gYWxsb3cgZXJyb3IKcGFja2FnZSBtYWluCgppbXBvcnQgKAoJImVycm9ycyIKCSJmbXQiCikKCi8vIDpzaG93IHN0YXJ0Ci8vIEZtdEFyZ3MgZm9ybWF0cyBhcmdzIGFzIGEgc3RyaW5nLiBGaXJzdCBhcmd1bWVudCBzaG91bGQgYmUgZm9ybWF0IHN0cmluZwovLyBhbmQgdGhlIHJlc3QgYXJlIGFyZ3VtZW50cyB0byB0aGUgZm9ybWF0CmZ1bmMgRm10QXJncyhhcmdzIC4uLmludGVyZmFjZXt9KSBzdHJpbmcgewoJaWYgbGVuKGFyZ3MpID09IDAgewoJCXJldHVybiAiIgoJfQoJZm9ybWF0IDo9IGFyZ3NbMF0uKHN0cmluZykKCWlmIGxlbihhcmdzKSA9PSAxIHsKCQlyZXR1cm4gZm9ybWF0Cgl9CglyZXR1cm4gZm10LlNwcmludGYoZm9ybWF0LCBhcmdzWzE6XS4uLikKfQoKZnVuYyBwYW5pY1dpdGhNc2coZGVmYXVsdE1zZyBzdHJpbmcsIGFyZ3MgLi4uaW50ZXJmYWNle30pIHsKCXMgOj0gRm10QXJncyhhcmdzLi4uKQoJaWYgcyA9PSAiIiB7CgkJcyA9IGRlZmF1bHRNc2cKCX0KCWZtdC5QcmludGYoIiVzXG4iLCBzKQoJcGFuaWMocykKfQoKLy8gUGFuaWNJZiBwYW5pY3MgaWYgY29uZCBpcyB0cnVlCmZ1bmMgUGFuaWNJZihjb25kIGJvb2wsIGFyZ3MgLi4uaW50ZXJmYWNle30pIHsKCWlmICFjb25kIHsKCQlyZXR1cm4KCX0KCXBhbmljV2l0aE1zZygiUGFuaWNJZjogY29uZGl0aW9uIGZhaWxlZCIsIGFyZ3MuLi4pCn0KCi8vIFBhbmljSWZFcnIgcGFuaWNzIGlmIGVyciBpcyBub3QgbmlsCmZ1bmMgUGFuaWNJZkVycihlcnIgZXJyb3IsIGFyZ3MgLi4uaW50ZXJmYWNle30pIHsKCWlmIGVyciA9PSBuaWwgewoJCXJldHVybgoJfQoJcGFuaWNXaXRoTXNnKGVyci5FcnJvcigpLCBhcmdzLi4uKQp9CgpmdW5jIG1haW4oKSB7CglQYW5pY0lmRXJyKG5pbCkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBub3RoaW5nIGhhcHBlbnMKCVBhbmljSWZFcnIoZXJyb3JzLk5ldygidGhlcmUgd2FzIGFuIGVycm9yIikpIC8vIHdpbGwgcGFuaWMKfQoKLy8gOnNob3cgZW5k"},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// allow error
package main

import (
	"errors"
	"fmt"
)

// :show start
// FmtArgs formats args as a string. First argument should be format string
// and the rest are arguments to the format
func FmtArgs(args ...interface{}) string {
	if len(args) == 0 {
		return ""
	}
	format := args[0].(string)
	if len(args) == 1 {
		return format
	}
	return fmt.Sprintf(format, args[1:]...)
}

func panicWithMsg(defaultMsg string, args ...interface{}) {
	s := FmtArgs(args...)
	if s == "" {
		s = defaultMsg
	}
	fmt.Printf("%s\n", s)
	panic(s)
}

// PanicIf panics if cond is true
func PanicIf(cond bool, args ...interface{}) {
	if !cond {
		return
	}
	panicWithMsg("PanicIf: condition failed", args...)
}

// PanicIfErr panics if err is not nil
func PanicIfErr(err error, args ...interface{}) {
	if err == nil {
		return
	}
	panicWithMsg(err.Error(), args...)
}

func main() {
	PanicIfErr(nil)                              // nothing happens
	PanicIfErr(errors.New("there was an error")) // will panic
}

// :show end