From b8f964b4ff9c161101a820fa86fc11a25e4b879c Mon Sep 17 00:00:00 2001 From: matst80 Date: Sun, 10 Nov 2024 19:00:19 +0100 Subject: [PATCH] better error handling --- rpc-pool.go | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/rpc-pool.go b/rpc-pool.go index efbbcb8..2d54c0a 100644 --- a/rpc-pool.go +++ b/rpc-pool.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "strings" "sync" ) @@ -28,17 +27,17 @@ type RemoteGrain struct { Address string } -func NewRemoteGrain(id CartId, address string) *RemoteGrain { +func NewRemoteGrain(id CartId, address string) (*RemoteGrain, error) { client, err := CartDial(address) if err != nil { - return nil + return nil, err } return &RemoteGrain{ Id: id, Address: address, CartClient: client, - } + }, nil } func (g *RemoteGrain) HandleMessage(message *Message, isReplay bool) ([]byte, error) { @@ -81,16 +80,19 @@ func (p *RemoteGrainPool) findRemoteGrain(id CartId) *RemoteGrain { return grain } -func (p *RemoteGrainPool) findOrCreateGrain(id CartId) *RemoteGrain { +func (p *RemoteGrainPool) findOrCreateGrain(id CartId) (*RemoteGrain, error) { grain := p.findRemoteGrain(id) - if grain == nil { - grain = NewRemoteGrain(id, p.Host) + if grain == nil { + grain, err := NewRemoteGrain(id, p.Host) + if err != nil { + return nil, err + } p.mu.Lock() p.grains[id] = grain p.mu.Unlock() } - return grain + return grain, nil } func (p *RemoteGrainPool) Delete(id CartId) { @@ -101,10 +103,9 @@ func (p *RemoteGrainPool) Delete(id CartId) { func (p *RemoteGrainPool) Process(id CartId, messages ...Message) ([]byte, error) { var result []byte - var err error - grain := p.findOrCreateGrain(id) - if grain == nil { - return nil, fmt.Errorf("grain not found") + grain, err := p.findOrCreateGrain(id) + if err != nil { + return nil, err } for _, message := range messages { result, err = grain.HandleMessage(&message, false) @@ -113,9 +114,9 @@ func (p *RemoteGrainPool) Process(id CartId, messages ...Message) ([]byte, error } func (p *RemoteGrainPool) Get(id CartId) ([]byte, error) { - grain := p.findOrCreateGrain(id) - if grain == nil { - return nil, fmt.Errorf("grain not found") + grain, err := p.findOrCreateGrain(id) + if err != nil { + return nil, err } return grain.GetCurrentState() }