Skip to content

Commit

Permalink
refactor: optimize error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
trungnt1811 committed May 31, 2024
1 parent 45ff366 commit 9a4b51d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
4 changes: 2 additions & 2 deletions airdrop/chains/terra.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ func Terra() ([]banktypes.Balance, []config.Reward, int, error) {
if token.LT(tokenIn20Usd) {
continue
}
if totalTokenDelegate.IsZero() {

if totalTokenDelegate.IsZero() {
return nil, nil, 0, fmt.Errorf("total token delegate is zero, cannot proceed with airdrop calculation")
}
eveAirdrop := (eveAirdrop.MulInt64(int64(config.GetTerraConfig().Percent))).QuoInt64(100).Mul(token).QuoTruncate(totalTokenDelegate)
Expand Down
17 changes: 12 additions & 5 deletions airdrop/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,24 @@ import (
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

func handleHTTPError(err error, message string) error {
if err != nil {
return fmt.Errorf("%s: %w", message, err)
}
return nil
}

func MakeGetRequest(uri string) (*http.Response, error) {
// Create a new HTTP request
req, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
return nil, handleHTTPError(err, "failed to create HTTP request")
}

// Send the HTTP request and get the response
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send HTTP request: %w", err)
return nil, handleHTTPError(err, "failed to send HTTP request")
}

return res, nil
Expand Down Expand Up @@ -73,21 +80,21 @@ func GetLatestHeight(apiURL string) (string, error) {
}

if err := backoff.Retry(retryableRequest, exponentialBackoff); err != nil {
return "", fmt.Errorf("error making GET request to get latest height: %w", err)
return "", handleHTTPError(err, "error making GET request to get latest height")
}

defer response.Body.Close()

// Read the response body
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("error reading response body: %w", err)
return "", handleHTTPError(err, "error reading response body")
}

// Parse the response body into a NodeResponse struct
var data config.NodeResponse
if err := json.Unmarshal(responseBody, &data); err != nil {
return "", fmt.Errorf("error unmarshalling JSON: %w", err)
return "", handleHTTPError(err, "error unmarshalling JSON")
}

// Extract the latest block height from the response
Expand Down

0 comments on commit 9a4b51d

Please sign in to comment.