errors handling

This commit is contained in:
alessio 2016-07-13 12:32:54 +02:00
parent 86ba7a0aef
commit e4fe6f4758
2 changed files with 21 additions and 15 deletions

13
main.go
View File

@ -9,6 +9,13 @@ import (
func main() { func main() {
handle := func(err error) error{
if err != nil {
return cli.Exit(err, 86)
}
return nil
}
app := &cli.App{ app := &cli.App{
Name: "realize", Name: "realize",
Version: "1.0", Version: "1.0",
@ -28,9 +35,9 @@ func main() {
Usage: "create the initial config file", Usage: "create the initial config file",
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
t := realize.Init() t := realize.Init()
t.Create() _, err := t.Create()
fmt.Printf("Hello %q", c.String("run")) return handle(err)
return nil
}, },
}, },
}, },

View File

@ -3,6 +3,7 @@ package realize
import ( import (
"os" "os"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"errors"
) )
type Config struct { type Config struct {
@ -20,17 +21,15 @@ type Watchers struct{
Ext []string `yaml:"app_ext,omitempty"` Ext []string `yaml:"app_ext,omitempty"`
} }
// Check files exists // Check files exists
func Check(files ...string) []bool{ func Check(files ...string) (result []bool, err error){
var result []bool
for _, val := range files { for _, val := range files {
if _, err := os.Stat(val); err == nil { if _, err := os.Stat(val); err == nil {
result = append(result,true) result = append(result,true)
} }
result = append(result, false) result = append(result, false)
} }
return result return
} }
// Default value // Default value
@ -49,22 +48,22 @@ func Init() Config{
} }
// Create config yaml file // Create config yaml file
func (h *Config) Create() bool{ func (h *Config) Create() (result bool, err error){
var config = Check(h.File) config, err := Check(h.File)
if config[0] == false { if config[0] == false {
if w, err := os.Create(h.File); err == nil { if w, err := os.Create(h.File); err == nil {
defer w.Close() defer w.Close()
y, err := yaml.Marshal(h) y, err := yaml.Marshal(h)
_, err = w.WriteString(string(y))
if err != nil { if err != nil {
panic(err) os.Remove(h.File)
return false, err
} }
w.WriteString(string(y)) return true, nil
return true
}else{
panic(err)
} }
return false, err
} }
return false return false, errors.New("already exist")
} }
// Read config file // Read config file