Merge pull request #8594 from hashicorp/fix_vagrant_cloud_parse_errors

post-processor/vagrant-cloud: Update error handling for Vagrant Cloud API
This commit is contained in:
Wilken Rivera 2020-01-13 17:43:38 -05:00 committed by GitHub
commit 5138ca8c67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 4 deletions

View File

@ -26,14 +26,22 @@ type VagrantCloudClient struct {
} }
type VagrantCloudErrors struct { type VagrantCloudErrors struct {
Errors map[string][]string `json:"errors"` Errors []interface{} `json:"errors"`
} }
func (v VagrantCloudErrors) FormatErrors() string { func (v VagrantCloudErrors) FormatErrors() string {
errs := make([]string, 0) errs := make([]string, 0)
for e := range v.Errors { for _, err := range v.Errors {
msg := fmt.Sprintf("%s %s", e, strings.Join(v.Errors[e], ",")) switch e := err.(type) {
errs = append(errs, msg) case string:
errs = append(errs, e)
case map[string]interface{}:
for k, v := range e {
errs = append(errs, fmt.Sprintf("%s %s", k, v))
}
default:
errs = append(errs, fmt.Sprintf("%s", err))
}
} }
return strings.Join(errs, ". ") return strings.Join(errs, ". ")
} }

View File

@ -0,0 +1,30 @@
package vagrantcloud
import (
"encoding/json"
"strings"
"testing"
)
func TestVagranCloudErrors(t *testing.T) {
testCases := []struct {
resp string
expected string
}{
{`{"Status":"422 Unprocessable Entity", "StatusCode":422, "errors":[]}`, ""},
{`{"Status":"404 Artifact not found", "StatusCode":404, "errors":["error1", "error2"]}`, "error1. error2"},
{`{"StatusCode":403, "errors":[{"message":"Bad credentials"}]}`, "message Bad credentials"},
{`{"StatusCode":500, "errors":[["error in unexpected format"]]}`, "[error in unexpected format]"},
}
for _, tc := range testCases {
var cloudErrors VagrantCloudErrors
err := json.NewDecoder(strings.NewReader(tc.resp)).Decode(&cloudErrors)
if err != nil {
t.Errorf("failed to decode error response: %s", err)
}
if got := cloudErrors.FormatErrors(); got != tc.expected {
t.Errorf("failed to get expected response; expected %q, got %q", tc.expected, got)
}
}
}