Skip to content

Commit bcf18ff

Browse files
committed
fix(error): parse and show the error message of unprocessable exception
1 parent c71a2e5 commit bcf18ff

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

errors.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,19 @@ var (
8484
ErrTagNotFound = errors.New(invalidTagMsg)
8585
// ErrDuplicateApp is returned when create an app with an ID that already exists
8686
ErrDuplicateApp = errors.New(duplicateIDMsg)
87-
// ErrUnprocessable is returned when the controller throws a 422.
88-
ErrUnprocessable = errors.New("Unable to process your request.")
8987
// ErrCancellationFailed is returned when cancelling a user fails.
9088
ErrCancellationFailed = errors.New("Failed to delete user because the user still has applications assigned. Delete or transfer ownership.")
9189
)
9290

91+
// ErrUnprocessable is returned when the controller throws a 422.
92+
type ErrUnprocessable struct {
93+
errorMsg string
94+
}
95+
96+
func (e ErrUnprocessable) Error() string {
97+
return fmt.Sprintf("Unable to process your request: %s", e.errorMsg)
98+
}
99+
93100
// checkForErrors tries to match up an API error with an predefined error in the SDK.
94101
func checkForErrors(res *http.Response) error {
95102
if res.StatusCode >= 200 && res.StatusCode < 400 {
@@ -205,7 +212,14 @@ func checkForErrors(res *http.Response) error {
205212
}
206213
return unknownServerError(res.StatusCode, string(out))
207214
case 422:
208-
return ErrUnprocessable
215+
bodyMap := make(map[string]interface{})
216+
if err := json.Unmarshal(out, &bodyMap); err != nil {
217+
return unknownServerError(res.StatusCode, fmt.Sprintf(jsonParsingError, err, string(out)))
218+
}
219+
if v, ok := bodyMap["detail"].(string); ok {
220+
return ErrUnprocessable{v}
221+
}
222+
return unknownServerError(res.StatusCode, string(out))
209223
case 500:
210224
return ErrServerError
211225
default:

errors_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,9 +260,9 @@ func TestErrors(t *testing.T) {
260260
{
261261
res: &http.Response{
262262
StatusCode: 422,
263-
Body: readCloser(""),
263+
Body: readCloser(`{"detail":"test does not exist under values"}`),
264264
},
265-
expected: ErrUnprocessable,
265+
expected: ErrUnprocessable{"test does not exist under values"},
266266
},
267267
{
268268
res: &http.Response{

0 commit comments

Comments
 (0)