Merge pull request #2295 from neilotoole/issue-2292

Re #2292 : The generated API should now return an err for non-2xx status codes
This commit is contained in:
wing328 2016-03-02 17:48:49 +08:00
commit a57bc98f59

View File

@ -4,6 +4,8 @@ package {{packageName}}
import (
"strings"
"fmt"
"encoding/json"
"errors"
"github.com/dghubble/sling"
{{#imports}} "{{import}}"
{{/imports}}
@ -68,16 +70,39 @@ func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{
{{#hasBodyParam}}{{#bodyParams}}// body params
_sling = _sling.BodyJSON({{paramName}})
{{/bodyParams}}{{/hasBodyParam}}
{{#returnType}} var successPayload = new({{returnType}}){{/returnType}}
{{#returnType}} response := new({{returnType}})
_, err := _sling.ReceiveSuccess(response)
//fmt.Println("{{operationId}} response: ", response, resp, err)
return *response, err
{{/returnType}}{{^returnType}}
_, err := _sling.ReceiveSuccess(nil)
//fmt.Println("{{operationId}} response: void, ", resp, err)
return err
{{/returnType}}
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive({{#returnType}}successPayload{{/returnType}}{{^returnType}}nil{{/returnType}}, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
}
return {{#returnType}}*successPayload, {{/returnType}}err
}
{{/operation}}
{{/operations}}