From 7082fbf5e3274ce09e8d9cb1ab020b59980089ae Mon Sep 17 00:00:00 2001 From: Peter Banik Date: Mon, 12 Aug 2024 11:48:15 +0200 Subject: [PATCH] Parse Binance API error response --- client/mm/libxc/binance.go | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/client/mm/libxc/binance.go b/client/mm/libxc/binance.go index af41a9527f..abf410d818 100644 --- a/client/mm/libxc/binance.go +++ b/client/mm/libxc/binance.go @@ -12,6 +12,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "math" "net/http" "net/url" @@ -27,7 +28,6 @@ import ( "decred.org/dcrdex/client/mm/libxc/bntypes" "decred.org/dcrdex/dex" "decred.org/dcrdex/dex/calc" - "decred.org/dcrdex/dex/dexnet" "decred.org/dcrdex/dex/encode" "decred.org/dcrdex/dex/utils" ) @@ -1915,7 +1915,38 @@ func binanceMarketToDexMarkets(binanceBaseSymbol, binanceQuoteSymbol string, tok return markets } +type BNApiResponse struct { + Code int `json:"code"` + Msg string `json:"msg"` +} + func requestInto(req *http.Request, thing interface{}) error { - // bnc.log.Tracef("Sending request: %+v", req) - return dexnet.Do(req, thing, dexnet.WithSizeLimit(1<<24)) + var sizeLimit int64 = 1 << 24 + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("error performing request: %w", err) + } + defer resp.Body.Close() + // Binance returns 400 Bad Request for errors + if resp.StatusCode == http.StatusBadRequest { + var apiResp BNApiResponse + reader := io.LimitReader(resp.Body, sizeLimit) + if err = json.NewDecoder(reader).Decode(&apiResp); err != nil { + return fmt.Errorf("error decoding response: %w", err) + } + return fmt.Errorf("API error: %s (%d)", apiResp.Msg, apiResp.Code) + } + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("HTTP error: %q (code %d)", resp.Status, resp.StatusCode) + } + if thing == nil { + return nil + } + reader := io.LimitReader(resp.Body, sizeLimit) + if err = json.NewDecoder(reader).Decode(thing); err != nil { + return fmt.Errorf("error decoding request: %w", err) + } + return nil }