Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In cases of non 20x responses, return an error from Execute() #11

Merged
merged 3 commits into from
Jul 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down