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 2 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
30 changes: 27 additions & 3 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"
)

// ExecuteErrorResponse 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 ExecuteErrorResponse struct {
yusufpapurcu marked this conversation as resolved.
Show resolved Hide resolved
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,14 +28,27 @@ 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
}

respbody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
respbody, rerr := io.ReadAll(resp.Body)
yusufpapurcu marked this conversation as resolved.
Show resolved Hide resolved
if rerr != nil {
return nil, rerr
}

// If we didnt get 20x response, unmarshal the error body to be able to format
yusufpapurcu marked this conversation as resolved.
Show resolved Hide resolved
// an informative error message. Mayb this should be >= 400, since I doubt redirect
// errors are returned.. but to be safe
if resp.StatusCode >= 300 {
yusufpapurcu marked this conversation as resolved.
Show resolved Hide resolved
var errmsg *ExecuteErrorResponse
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()
Expand Down