Skip to content

Commit

Permalink
context: add ResponseError()
Browse files Browse the repository at this point in the history
  • Loading branch information
lesismal committed Jun 2, 2024
1 parent b7cc664 commit eb50202
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
13 changes: 11 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ type Context struct {
Client *Client
Message *Message

index int
handlers []HandlerFunc
index int
handlers []HandlerFunc
responseErr interface{}
}

func (ctx *Context) Release() {
Expand All @@ -35,6 +36,10 @@ func (ctx *Context) Release() {
contextPool.Put(ctx)
}

func (ctx *Context) ResponseError() interface{} {
return ctx.responseErr
}

// Get returns value for key.
func (ctx *Context) Get(key interface{}) (interface{}, bool) {
if len(ctx.Message.values) == 0 {
Expand Down Expand Up @@ -153,6 +158,10 @@ func (ctx *Context) write(v interface{}, isError bool, timeout time.Duration) er
if _, ok := v.(error); ok {
isError = true
}
if isError {
ctx.responseErr = v
}

rsp := newMessage(CmdResponse, req.method(), v, isError, req.IsAsync(), req.Seq(), cli.Handler, cli.Codec, ctx.Message.values)
return cli.PushMsg(rsp, timeout)
}
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package arpc

import (
"errors"
"testing"

"github.com/lesismal/arpc/codec"
Expand Down Expand Up @@ -110,3 +111,15 @@ func TestContext_Value(t *testing.T) {
t.Fatalf("Context.Value() value != 'value', have %v", value)
}
}

func TestContext_ResponseError(t *testing.T) {
ctx := &Context{
Client: &Client{Handler: DefaultHandler},
Message: newMessage(CmdRequest, "test", nil, false, false, 0, DefaultHandler, codec.DefaultCodec, nil),
}
err := errors.New("test err")
ctx.Error(err)
if ctx.ResponseError() != err {
t.Fatalf("Context.ResponseError() != 'test err'")
}
}

0 comments on commit eb50202

Please sign in to comment.