diff --git a/execute.go b/execute.go index 3bf25f7..521aab6 100644 --- a/execute.go +++ b/execute.go @@ -3,10 +3,21 @@ package postgrest import ( "bytes" "encoding/json" + "fmt" "io" "net/http" ) +// ExecuteError is the error response format from postgrest. We really +// only use Code and Message, but we'll keep it as a struct for now. + +type ExecuteError struct { + Hint string `json:"hint"` + Details string `json:"details"` + Code string `json:"code"` + Message string `json:"message"` +} + func executeHelper(client *Client, method string, body []byte) ([]byte, error) { if client.ClientError != nil { return nil, client.ClientError @@ -17,6 +28,7 @@ func executeHelper(client *Client, method string, body []byte) ([]byte, error) { if err != nil { return nil, err } + resp, err := client.session.Do(req) if err != nil { return nil, err @@ -27,6 +39,16 @@ func executeHelper(client *Client, method string, body []byte) ([]byte, error) { return nil, err } + // https://postgrest.org/en/stable/api.html#errors-and-http-status-codes + if resp.StatusCode >= 400 { + var errmsg *ExecuteError + err := json.Unmarshal(respbody, &errmsg) + if err != nil { + return nil, err + } + return nil, fmt.Errorf("(%s) %s", errmsg.Code, errmsg.Message) + } + err = resp.Body.Close() if err != nil { return nil, err