Skip to content

Commit

Permalink
Merge pull request #835 from iotaledger/improve-errors
Browse files Browse the repository at this point in the history
Fix error wrapping order
  • Loading branch information
PhilippGackstatter authored Mar 15, 2024
2 parents 4082e5a + f87ad11 commit b0aed00
Show file tree
Hide file tree
Showing 66 changed files with 307 additions and 323 deletions.
18 changes: 9 additions & 9 deletions components/dashboard/explorer_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ func setupExplorerRoutes(routeGroup *echo.Group) {
routeGroup.GET("/block/:"+api.ParameterBlockID, func(c echo.Context) (err error) {
blockID, err := httpserver.ParseBlockIDParam(c, api.ParameterBlockID)
if err != nil {
return ierrors.Errorf("parse block ID error: %w", err)
return ierrors.Wrap(err, "failed to parse block ID")
}

t, err := findBlock(blockID)
if err != nil {
return ierrors.Errorf("find block error: %w", err)
return err
}

return c.JSON(http.StatusOK, t)
Expand All @@ -53,12 +53,12 @@ func setupExplorerRoutes(routeGroup *echo.Group) {

blockID, err := iotago.BlockIDFromHexString(search)
if err != nil {
return ierrors.Wrapf(ErrInvalidParameter, "search ID %s", search)
return ierrors.WithMessagef(ErrInvalidParameter, "search ID %s", search)
}

blk, err := findBlock(blockID)
if err != nil {
return ierrors.Errorf("can't find block %s: %w", search, err)
return err
}
result.Block = blk

Expand All @@ -75,14 +75,14 @@ func setupExplorerRoutes(routeGroup *echo.Group) {
func findBlock(blockID iotago.BlockID) (explorerBlk *ExplorerBlock, err error) {
block, exists := deps.Protocol.Engines.Main.Get().Block(blockID)
if !exists {
return nil, ierrors.Errorf("block not found: %s", blockID.ToHex())
return nil, ierrors.Errorf("block %s not found", blockID)
}

cachedBlock, _ := deps.Protocol.Engines.Main.Get().BlockCache.Block(blockID)

blockMetadata, err := deps.Protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID)
if err != nil {
return nil, ierrors.Wrapf(err, "block metadata %s", blockID.ToHex())
return nil, ierrors.Wrapf(err, "failed to get block metadata for block %s", blockID)
}

return createExplorerBlock(block, cachedBlock, blockMetadata), nil
Expand Down Expand Up @@ -201,12 +201,12 @@ func getTransaction(c echo.Context) error {

block, exists := deps.Protocol.Engines.Main.Get().Block(output.BlockID())
if !exists {
return ierrors.Errorf("block not found: %s", output.BlockID().ToHex())
return ierrors.Errorf("block %s not found", output.BlockID().ToHex())
}

iotaTX, isTX := block.SignedTransaction()
if !isTX {
return ierrors.Errorf("payload is not a signed transaction: %s", output.BlockID().ToHex())
return ierrors.Errorf("block payload of block %s is not a signed transaction", output.BlockID().ToHex())
}

return httpserver.JSONResponse(c, http.StatusOK, NewTransaction(iotaTX))
Expand All @@ -223,7 +223,7 @@ func getTransactionMetadata(c echo.Context) error {
copy(outputID[:], txID[:])
txMetadata, exists := deps.Protocol.Engines.Main.Get().Ledger.MemPool().TransactionMetadata(txID)
if !exists {
return ierrors.Errorf("tx metadata not found: %s", txID.ToHex())
return ierrors.Errorf("transaction metadata for transaction %s not found", txID.ToHex())
}

conflicts, _ := deps.Protocol.Engines.Main.Get().Ledger.SpendDAG().ConflictingSpenders(txID)
Expand Down
2 changes: 1 addition & 1 deletion components/debugapi/blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func getSlotBlockIDs(index iotago.SlotIndex) (*BlockChangesResponse, error) {
_ = blocksForSlot.StreamKeys(func(blockID iotago.BlockID) error {
includedBlocks = append(includedBlocks, blockID.String())
if err := tangleTree.Add(blockID); err != nil {
return ierrors.Wrapf(err, "failed to add block to tangle tree, blockID: %s", blockID.ToHex())
return ierrors.Wrapf(err, "failed to add block to tangle tree, blockID: %s", blockID)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion components/inx/server_blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func (s *Server) attachBlock(ctx context.Context, block *iotago.Block) (*inx.Blo
func getINXBlockMetadata(blockID iotago.BlockID) (*inx.BlockMetadata, error) {
blockMetadata, err := deps.Protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID)
if err != nil {
return nil, ierrors.Errorf("failed to get BlockMetadata: %v", err)
return nil, ierrors.Wrap(err, "failed to get BlockMetadata")
}

return inx.WrapBlockMetadata(blockMetadata)
Expand Down
6 changes: 3 additions & 3 deletions components/inx/server_commitments.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List
}

if err := srv.Send(inxCommitment(commitment)); err != nil {
return ierrors.Errorf("send error: %w", err)
return ierrors.Wrap(err, "send error")
}

return nil
Expand Down Expand Up @@ -108,7 +108,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List
catchUpFunc := func(start iotago.SlotIndex, end iotago.SlotIndex) error {
err := sendSlotsRange(start, end)
if err != nil {
err := ierrors.Errorf("sendSlotsRange error: %w", err)
err := ierrors.Wrap(err, "sendSlotsRange error")
Component.LogError(err.Error())

return err
Expand All @@ -119,7 +119,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List

sendFunc := func(_ iotago.SlotIndex, payload *inx.Commitment) error {
if err := srv.Send(payload); err != nil {
err := ierrors.Errorf("send error: %w", err)
err := ierrors.Wrap(err, "send error")
Component.LogError(err.Error())

return err
Expand Down
7 changes: 5 additions & 2 deletions components/inx/server_issuance.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package inx
import (
"context"

"github.com/iotaledger/hive.go/ierrors"
"github.com/iotaledger/hive.go/lo"
"github.com/iotaledger/hive.go/serializer/v2/serix"
inx "github.com/iotaledger/inx/go"
Expand Down Expand Up @@ -58,8 +57,12 @@ func (s *Server) ValidatePayload(_ context.Context, payload *inx.RawPayload) (*i
// TaggedData is always valid if serix decoding was successful
return nil

case *iotago.CandidacyAnnouncement:
panic("TODO: implement me")
default:
return ierrors.Errorf("unsupported payload type: %T", typedPayload)
// We're switching on the Go payload type here, so we can only run into the default case
// if we added a new payload type and have not handled it above. In this case we want to panic.
panic("all supported payload types should be handled above")
}
}(); err != nil {
//nolint:nilerr // this is expected behavior
Expand Down
2 changes: 1 addition & 1 deletion components/inx/server_transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (s *Server) ReadTransactionMetadata(_ context.Context, transactionID *inx.T
return nil, status.Errorf(codes.NotFound, "transaction metadata not found: %s", txID.ToHex())
}

return nil, ierrors.WithMessagef(err, "error when retrieving transaction metadata: %s", txID.ToHex())
return nil, ierrors.Wrapf(err, "error when retrieving transaction metadata: %s", txID.ToHex())
}

return inx.WrapTransactionMetadata(txMetadata), nil
Expand Down
11 changes: 5 additions & 6 deletions components/inx/server_utxo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package inx

import (
"context"
"fmt"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
Expand Down Expand Up @@ -189,7 +188,7 @@ func (s *Server) ReadUnspentOutputs(_ *inx.NoParams, srv inx.INX_ReadUnspentOutp
}

if err := srv.Send(payload); err != nil {
innerErr = fmt.Errorf("send error: %w", err)
innerErr = ierrors.Wrap(err, "send error")

return false
}
Expand All @@ -212,7 +211,7 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li

// Send Begin
if err := srv.Send(NewLedgerUpdateBatchBegin(commitment.ID(), len(outputs), len(spents))); err != nil {
return fmt.Errorf("send error: %w", err)
return ierrors.Wrap(err, "send error")
}

// Send consumed
Expand All @@ -223,7 +222,7 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li
}

if err := srv.Send(payload); err != nil {
return fmt.Errorf("send error: %w", err)
return ierrors.Wrap(err, "send error")
}
}

Expand All @@ -235,13 +234,13 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li
}

if err := srv.Send(payload); err != nil {
return fmt.Errorf("send error: %w", err)
return ierrors.Wrap(err, "send error")
}
}

// Send End
if err := srv.Send(NewLedgerUpdateBatchEnd(commitment.ID(), len(outputs), len(spents))); err != nil {
return fmt.Errorf("send error: %w", err)
return ierrors.Wrap(err, "send error")
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion components/p2p/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ func getMultiAddrsFromString(peers []string) ([]multiaddr.Multiaddr, error) {
for _, peer := range peers {
peerMultiAddr, err := multiaddr.NewMultiaddr(peer)
if err != nil {
return nil, ierrors.Errorf("invalid peer multiaddr \"%s\": %w", peer, err)
return nil, ierrors.Wrapf(err, "invalid peer multiaddr \"%s\"", peer)
}
peersMultiAddresses = append(peersMultiAddresses, peerMultiAddr)
}
Expand Down
2 changes: 1 addition & 1 deletion components/p2p/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func initPeerDB() (peerDB *network.DB, peerDBKVStore kvstore.KVStore, err error)

db, err := database.NewRocksDB(ParamsP2P.Database.Path)
if err != nil {
return nil, nil, ierrors.Wrap(err, "error creating peer database")
return nil, nil, ierrors.Wrap(err, "failed to create peer database")
}

peerDBKVStore = rocksdb.New(db)
Expand Down
2 changes: 1 addition & 1 deletion components/prometheus/metrics_scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ var SchedulerMetrics = collector.NewCollection(schedulerNamespace,
deps.Protocol.Events.Engine.Scheduler.BlockEnqueued.Hook(func(block *blocks.Block) {
mana, err := deps.Protocol.Engines.Main.Get().Ledger.ManaManager().GetManaOnAccount(block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())
if err != nil {
deps.Protocol.Engines.Main.Get().ErrorHandler("metrics")(ierrors.Wrapf(err, "failed to retrieve mana on account %s for slot %d", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot()))
deps.Protocol.Engines.Main.Get().ErrorHandler("metrics")(ierrors.Wrapf(err, "failed to retrieve mana on account %s for slot %d", block.ProtocolBlock().Header.IssuerID.ToHex(), block.SlotCommitmentID().Slot()))

return
}
Expand Down
2 changes: 1 addition & 1 deletion components/restapi/core/blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func sendBlock(c echo.Context) (*api.BlockCreatedResponse, error) {

blockID, err := deps.RequestHandler.AttachBlock(c.Request().Context(), iotaBlock)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to attach block: %w", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to attach block: %w", err)
}

return &api.BlockCreatedResponse{
Expand Down
2 changes: 1 addition & 1 deletion components/restapi/core/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func checkNodeSynced() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !deps.RequestHandler.IsNodeSynced() {
return ierrors.Wrap(echo.ErrServiceUnavailable, "node is not synced")
return ierrors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}

return next(c)
Expand Down
4 changes: 2 additions & 2 deletions components/restapi/core/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func blockIDFromTransactionID(c echo.Context) (iotago.BlockID, error) {
func blockFromTransactionID(c echo.Context) (*iotago.Block, error) {
blockID, err := blockIDFromTransactionID(c)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrBadRequest, "failed to get block ID by transaction ID: %s", err)
return nil, ierrors.WithMessagef(echo.ErrBadRequest, "failed to get block ID by transaction ID: %w", err)
}

block, err := deps.RequestHandler.BlockByID(blockID)
Expand All @@ -35,7 +35,7 @@ func blockFromTransactionID(c echo.Context) (*iotago.Block, error) {
func blockMetadataFromTransactionID(c echo.Context) (*api.BlockMetadataResponse, error) {
blockID, err := blockIDFromTransactionID(c)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrBadRequest, "failed to get block ID by transaction ID: %s", err)
return nil, ierrors.WithMessagef(echo.ErrBadRequest, "failed to get block ID by transaction ID: %w", err)
}

return deps.RequestHandler.BlockMetadataByBlockID(blockID)
Expand Down
14 changes: 7 additions & 7 deletions components/restapi/management/pruning.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,47 @@ import (

func pruneDatabase(c echo.Context) (*api.PruneDatabaseResponse, error) {
if deps.Protocol.Engines.Main.Get().Storage.IsPruning() {
return nil, ierrors.Wrapf(echo.ErrServiceUnavailable, "node is already pruning")
return nil, ierrors.WithMessage(echo.ErrServiceUnavailable, "node is already pruning")
}

request := &api.PruneDatabaseRequest{}
if err := c.Bind(request); err != nil {
return nil, ierrors.Wrapf(httpserver.ErrInvalidParameter, "invalid request, error: %s", err)
return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request, error: %w", err)
}

// only allow one type of pruning at a time
if (request.Epoch == 0 && request.Depth == 0 && request.TargetDatabaseSize == "") ||
(request.Epoch != 0 && request.Depth != 0) ||
(request.Epoch != 0 && request.TargetDatabaseSize != "") ||
(request.Depth != 0 && request.TargetDatabaseSize != "") {
return nil, ierrors.Wrapf(httpserver.ErrInvalidParameter, "either epoch, depth or size has to be specified")
return nil, ierrors.WithMessage(httpserver.ErrInvalidParameter, "either epoch, depth or size has to be specified")
}

var err error

if request.Epoch != 0 {
err = deps.Protocol.Engines.Main.Get().Storage.PruneByEpochIndex(request.Epoch)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err)
}
}

if request.Depth != 0 {
_, _, err := deps.Protocol.Engines.Main.Get().Storage.PruneByDepth(request.Depth)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err)
}
}

if request.TargetDatabaseSize != "" {
pruningTargetDatabaseSizeBytes, err := bytes.Parse(request.TargetDatabaseSize)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err)
}

err = deps.Protocol.Engines.Main.Get().Storage.PruneBySize(pruningTargetDatabaseSizeBytes)
if err != nil {
return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err)
}
}

Expand Down
4 changes: 2 additions & 2 deletions components/restapi/management/snapshots.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func createSnapshots(_ echo.Context) (*api.CreateSnapshotResponse, error) {
request := &createSnapshotsRequest{}
if err := c.Bind(request); err != nil {
return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request, error: %s", err)
return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request: %w", err)
}
if request.Slot == 0 {
Expand All @@ -23,7 +23,7 @@ func createSnapshots(_ echo.Context) (*api.CreateSnapshotResponse, error) {
filePath := filepath.Join(filepath.Dir(deps.SnapshotsFullPath), fmt.Sprintf("full_snapshot_%d.bin", request.Slot))
if err := deps.SnapshotManager.CreateFullSnapshot(Component.Daemon().ContextStopped(), request.Slot, filePath, false); err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "creating snapshot failed: %s", err)
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "creating snapshot failed: %w", err)
}
return &createSnapshotsResponse{
Expand Down
6 changes: 3 additions & 3 deletions pkg/jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func NewAuth(subject string, sessionTimeout time.Duration, nodeID string, secret

secretBytes, err := crypto.MarshalPrivateKey(secret)
if err != nil {
return nil, ierrors.Errorf("unable to convert private key: %w", err)
return nil, ierrors.Wrap(err, "unable to convert private key")
}

return &Auth{
Expand Down Expand Up @@ -98,7 +98,7 @@ func (j *Auth) Middleware(skipper middleware.Skipper, allow func(c echo.Context,

// validate the signing method we expect
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return ierrors.Errorf("unexpected signing method: %v", token.Header["alg"])
return ierrors.Errorf("unexpected signing method: %s", token.Method.Alg())
}

// read the claims set by the JWT middleware on the context
Expand Down Expand Up @@ -154,7 +154,7 @@ func (j *Auth) VerifyJWT(token string, allow func(claims *AuthClaims) bool) bool
t, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(token *jwt.Token) (interface{}, error) {
// validate the signing method we expect
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, ierrors.Errorf("unexpected signing method: %v", token.Header["alg"])
return nil, ierrors.Errorf("unexpected signing method: %s", token.Method.Alg())
}

return j.secret, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (blk *Block) String() string {
panic(err)
}
var out bytes.Buffer
if json.Indent(&out, encode, "", " ") != nil {
if err = json.Indent(&out, encode, "", " "); err != nil {
panic(err)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/model/commitment.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (c *Commitment) String() string {
panic(err)
}
var out bytes.Buffer
if json.Indent(&out, encode, "", " ") != nil {
if err = json.Indent(&out, encode, "", " "); err != nil {
panic(err)
}

Expand Down
Loading

0 comments on commit b0aed00

Please sign in to comment.