Skip to content

Commit 7de6ebe

Browse files
committed
fix vikstrous#15 add a default panic handler
1 parent e8a1cfc commit 7de6ebe

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

dataloadgen.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ func (l *Loader[KeyT, ValueT]) startBatch(ctx context.Context) {
273273
}
274274
}
275275

276-
batch.results, batch.errors = l.fetch(batch.firstContext, batch.keys)
276+
batch.results, batch.errors = l.safeFetch(batch.firstContext, batch.keys)
277277

278278
if l.tracer != nil {
279279
for _, span := range spans {
@@ -286,6 +286,16 @@ func (l *Loader[KeyT, ValueT]) startBatch(ctx context.Context) {
286286
}
287287
}
288288

289+
func (l *Loader[KeyT, ValueT]) safeFetch(ctx context.Context, keys []KeyT) (values []ValueT, errs []error) {
290+
defer func() {
291+
panicValue := recover()
292+
if panicValue != nil {
293+
errs = []error{fmt.Errorf("panic during fetch: %v", panicValue)}
294+
}
295+
}()
296+
return l.fetch(ctx, keys)
297+
}
298+
289299
// addKeyToBatch will return the location of the key in the batch, if its not found
290300
// it will add the key to the batch
291301
func (l *Loader[KeyT, ValueT]) addKeyToBatch(b *loaderBatch[KeyT, ValueT], key KeyT) int {
@@ -305,7 +315,7 @@ func (l *Loader[KeyT, ValueT]) addKeyToBatch(b *loaderBatch[KeyT, ValueT], key K
305315
}
306316
}
307317

308-
b.results, b.errors = l.fetch(b.firstContext, b.keys)
318+
b.results, b.errors = l.safeFetch(b.firstContext, b.keys)
309319

310320
if l.tracer != nil {
311321
for _, span := range spans {

dataloadgen_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,16 @@ func TestErrors(t *testing.T) {
108108
t.Fatalf("wrong error: %s", errs[2].Error())
109109
}
110110
}
111+
112+
func TestPanic(t *testing.T) {
113+
ctx := context.Background()
114+
dl := dataloadgen.NewLoader(func(_ context.Context, keys []int) ([]string, []error) {
115+
panic("fetch panic")
116+
},
117+
dataloadgen.WithBatchCapacity(1),
118+
)
119+
_, err := dl.Load(ctx, 1)
120+
if err.Error() != "panic during fetch: fetch panic" {
121+
t.Fatalf("wrong error: %s", err.Error())
122+
}
123+
}

0 commit comments

Comments
 (0)