Skip to content

Commit

Permalink
Merge pull request #67 from ovh/dev/rbeuque/errors
Browse files Browse the repository at this point in the history
feat(errors): improve readability of error messages
  • Loading branch information
rbeuque74 authored Mar 30, 2023
2 parents a85722d + c983894 commit bb87c54
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
36 changes: 31 additions & 5 deletions ovh/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package ovh

import "fmt"
import (
"fmt"
"strings"
)

// APIError represents an error that can occurred while calling the API.
type APIError struct {
Expand All @@ -16,10 +19,33 @@ type APIError struct {
QueryID string
}

func (err *APIError) Error() string {
if err.Class == "" {
return fmt.Sprintf("HTTP Error %d: %q", err.Code, err.Message)
// Let's make sure that APIError always satisfies the fmt.Stringer and error interfaces
var _ fmt.Stringer = APIError{}
var _ error = APIError{}

func (err APIError) Error() string {
var sb strings.Builder
sb.Grow(128)

// Base message
fmt.Fprint(&sb, "OVHcloud API error (status code ", err.Code, "): ")

// Append class if any
if err.Class != "" {
fmt.Fprint(&sb, err.Class, ": ")
}

// Real error message, quoted
fmt.Fprintf(&sb, "%q", err.Message)

// QueryID if any
if err.QueryID != "" {
fmt.Fprint(&sb, " (X-OVH-Query-Id: ", err.QueryID, ")")
}

return fmt.Sprintf("HTTP Error %d: %s: %q (X-OVH-Query-Id: %s)", err.Code, err.Class, err.Message, err.QueryID)
return sb.String()
}

func (err APIError) String() string {
return err.Error()
}
20 changes: 15 additions & 5 deletions ovh/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,27 @@ import (
)

func TestErrorString(t *testing.T) {
err := &APIError{
err := APIError{
Code: http.StatusBadRequest,
Message: "Bad request",
Message: "An input error occurred",
}
td.CmpString(t, err, `HTTP Error 400: "Bad request"`)
expected := `OVHcloud API error (status code 400): "An input error occurred"`
td.Cmp(t, err.Error(), expected)
td.Cmp(t, err.String(), expected)

err = &APIError{
err = APIError{
Code: http.StatusConflict,
Message: `the cart id "foobar" already exists`,
Class: "CartAlreadyExists",
QueryID: "EU.ext-99.foobar",
}
td.CmpString(t, err, `HTTP Error 409: CartAlreadyExists: "the cart id \"foobar\" already exists" (X-OVH-Query-Id: EU.ext-99.foobar)`)
expected = `OVHcloud API error (status code 409): CartAlreadyExists: "the cart id \"foobar\" already exists" (X-OVH-Query-Id: EU.ext-99.foobar)`
td.Cmp(t, err.Error(), expected)
td.Cmp(t, err.String(), expected)

err.Class = ""
expected = `OVHcloud API error (status code 409): "the cart id \"foobar\" already exists" (X-OVH-Query-Id: EU.ext-99.foobar)`
td.Cmp(t, err.Error(), expected)
td.Cmp(t, err.String(), expected)

}

0 comments on commit bb87c54

Please sign in to comment.