Skip to content

Commit

Permalink
Externalize response error
Browse files Browse the repository at this point in the history
  • Loading branch information
gdeandradero committed Mar 18, 2024
1 parent c5e800b commit 320a613
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
37 changes: 37 additions & 0 deletions examples/mp_error_parse/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"context"
"errors"
"fmt"

"github.com/mercadopago/sdk-go/pkg/config"
"github.com/mercadopago/sdk-go/pkg/mperror"
"github.com/mercadopago/sdk-go/pkg/payment"
)

func main() {
accessToken := "{{ACCESS_TOKEN}}"

cfg, err := config.New(accessToken)
if err != nil {
fmt.Println(err)
return
}

invalidRequest := payment.Request{}

client := payment.NewClient(cfg)
payment, err := client.Create(context.Background(), invalidRequest)
if err != nil {
var mpErr *mperror.ResponseError
if errors.As(err, &mpErr) {
fmt.Printf("\nheaders: %s\nmessage: %s\nstatus code: %d", mpErr.Headers, mpErr.Message, mpErr.StatusCode)
return
}
fmt.Println(err)
return
}

fmt.Println(payment)
}
5 changes: 3 additions & 2 deletions pkg/internal/httpclient/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"net/http"

"github.com/mercadopago/sdk-go/pkg/mperror"
"github.com/mercadopago/sdk-go/pkg/requester"
)

Expand All @@ -18,15 +19,15 @@ func Send(requester requester.Requester, req *http.Request) ([]byte, error) {

response, err := io.ReadAll(result.Body)
if err != nil {
return nil, &ResponseError{
return nil, &mperror.ResponseError{
StatusCode: result.StatusCode,
Message: "error reading response body: " + err.Error(),
Headers: result.Header,
}
}

if result.StatusCode > 399 {
return nil, &ResponseError{
return nil, &mperror.ResponseError{
StatusCode: result.StatusCode,
Message: string(response),
Headers: result.Header,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package httpclient
package mperror

import "net/http"

Expand Down

0 comments on commit 320a613

Please sign in to comment.