Try to parse error string returned by server before falling back to generic message
authorRoberto Santalla <roobre@roobre.es>
Sat, 20 Apr 2019 14:21:48 +0200
changeset 248 f287d505dfda
parent 247 17e32e951670
child 249 3ba735776c8a
Try to parse error string returned by server before falling back to generic message Closes #4
api.go
--- a/api.go	Sun Jan 13 13:25:58 2019 +0100
+++ b/api.go	Sat Apr 20 14:21:48 2019 +0200
@@ -130,11 +130,22 @@
 		return nil, err
 	}
 	if res.StatusCode < 200 || res.StatusCode >= 300 {
+		var errorText string
+		// Try to unmarshal the returned error object for a description
+		mastodonError := Error{}
+		decodeErr := json.NewDecoder(res.Body).Decode(&mastodonError)
+		if decodeErr != nil {
+			// Decode unsuccessful, fallback to generic error based on response code
+			errorText = http.StatusText(res.StatusCode)
+		} else {
+			errorText = mastodonError.Text
+		}
+
 		// Please note that the error string code is used by Search()
 		// to check the error cause.
 		const errFormatString = "bad server status code (%d)"
 		return nil, errors.Errorf(errFormatString+": %s",
-			res.StatusCode, http.StatusText(res.StatusCode))
+			res.StatusCode, errorText)
 	}
 
 	// Build Response object.