forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_accumulator.go
53 lines (43 loc) · 930 Bytes
/
error_accumulator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package openai
import (
"bytes"
"fmt"
"io"
utils "github.com/sashabaranov/go-openai/internal"
)
type errorAccumulator interface {
write(p []byte) error
unmarshalError() *ErrorResponse
}
type errorBuffer interface {
io.Writer
Len() int
Bytes() []byte
}
type defaultErrorAccumulator struct {
buffer errorBuffer
unmarshaler utils.Unmarshaler
}
func newErrorAccumulator() errorAccumulator {
return &defaultErrorAccumulator{
buffer: &bytes.Buffer{},
unmarshaler: &utils.JSONUnmarshaler{},
}
}
func (e *defaultErrorAccumulator) write(p []byte) error {
_, err := e.buffer.Write(p)
if err != nil {
return fmt.Errorf("error accumulator write error, %w", err)
}
return nil
}
func (e *defaultErrorAccumulator) unmarshalError() (errResp *ErrorResponse) {
if e.buffer.Len() == 0 {
return
}
err := e.unmarshaler.Unmarshal(e.buffer.Bytes(), &errResp)
if err != nil {
errResp = nil
}
return
}