Skip to content

Commit

Permalink
Refactor error handling in CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksandr Tihomirov committed Jan 7, 2017
1 parent 6f17067 commit e13488d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 19 deletions.
33 changes: 17 additions & 16 deletions cmd/gowo/cmd/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,33 +33,32 @@ import (
"github.com/whats-this/owo.go"
)

func doUpload(cdn string, names []string) {
files, err := owo.FilesToNamedReaders(names)
func doUpload(cdn string, names []string) (err error) {
var files []owo.NamedReader
files, err = owo.FilesToNamedReaders(names)
if err != nil {
log.Println("[upload]", err)
return
}
response, err := owo.UploadFiles(context.Background(), files)
var response *owo.Response
response, err = owo.UploadFiles(context.Background(), files)
if err != nil {
log.Println("[upload]", err)
return
}
if !response.Success {
log.Printf("[upload] %d: %s", response.Errorcode, response.Description)
return
}
buf := bytes.Buffer{}
var url string
for _, file := range response.Files {
if file.Error {
log.Printf("%d: %s", file.Errorcode, file.Description)
continue
url, err = file.WithCDN(cdn)
if err != nil {
log.Println("[upload]", err)
}
fmt.Fprintf(&buf, "%s\n", file.WithCDN(cdn))
fmt.Fprintf(&buf, "%s\n", url)
}
if err := output(buf.String(), len(response.Files)); err != nil {
log.Println("[upload]", err)
err = output(buf.String(), len(response.Files))
if err != nil {
return
}
response = nil
return
}

// uploadCmd represents the upload command
Expand All @@ -72,7 +71,9 @@ var uploadCmd = &cobra.Command{
log.Fatal("Need at least one file.")
}
cdn := viper.GetString("cdn")
doUpload(cdn, args)
if err := doUpload(cdn, args); err != nil {
log.Fatal(err)
}
},
}

Expand Down
7 changes: 6 additions & 1 deletion cmd/gowo/cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ var watchCmd = &cobra.Command{
continue
}

go doUpload(cdn, names)
go func() {
err := doUpload(cdn, names)
if err != nil {
log.Print(err)
}
}()
}
}()

Expand Down
8 changes: 6 additions & 2 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ func (e ErrUploadFailed) Error() string {
}

// WithCDN returns file url prefixed with the CDN
func (f File) WithCDN(cdn string) string {
return cdn + f.URL
func (f File) WithCDN(cdn string) (string, error) {
if f.Error {
return "", ErrUploadFailed{f.Description, f.Errorcode}
}

return cdn + f.URL, nil
}

0 comments on commit e13488d

Please sign in to comment.