Skip to content

Commit

Permalink
Merge pull request #2027 from dubek/rest-api-block-not-in-db
Browse files Browse the repository at this point in the history
core/rest: Fix panic when block not found in DB
  • Loading branch information
srderson committed Jun 28, 2016
2 parents ce66cb6 + 5f1d584 commit 501996e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
39 changes: 20 additions & 19 deletions core/rest/rest_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -670,26 +670,27 @@ func (s *ServerOpenchainREST) GetBlockByNumber(rw web.ResponseWriter, req *web.R
// Failure
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Block id must be an integer (uint64)."})
} else {
// Retrieve Block from blockchain
block, err := s.server.GetBlockByNumber(context.Background(), &pb.BlockNumber{Number: blockNumber})

// Check for error
if err != nil || block == nil {
// Failure
switch {
case err == ErrNotFound || block == nil:
rw.WriteHeader(http.StatusNotFound)
default:
rw.WriteHeader(http.StatusInternalServerError)
}
encoder.Encode(restResult{Error: err.Error()})
} else {
// Success
rw.WriteHeader(http.StatusOK)
encoder.Encode(block)
}
return
}

// Retrieve Block from blockchain
block, err := s.server.GetBlockByNumber(context.Background(), &pb.BlockNumber{Number: blockNumber})

if (err == ErrNotFound) || (err == nil && block == nil) {
rw.WriteHeader(http.StatusNotFound)
encoder.Encode(restResult{Error: ErrNotFound.Error()})
return
}

if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: err.Error()})
return
}

// Success
rw.WriteHeader(http.StatusOK)
encoder.Encode(block)
}

// GetTransactionByUUID returns a transaction matching the specified UUID
Expand Down
8 changes: 8 additions & 0 deletions core/rest/rest_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,14 @@ func TestServerOpenchainREST_API_GetBlockByNumber(t *testing.T) {
if res.Error == "" {
t.Errorf("Expected an error when URL doesn't have a number, but got none")
}

// Add a fake block number 9 and try to fetch non-existing block 6
ledger.PutRawBlock(&block0, 9)
body = performHTTPGet(t, httpServer.URL+"/chain/blocks/6")
res = parseRESTResult(t, body)
if res.Error == "" {
t.Errorf("Expected an error when block doesn't exist, but got none")
}
}

func TestServerOpenchainREST_API_GetTransactionByUUID(t *testing.T) {
Expand Down

0 comments on commit 501996e

Please sign in to comment.