From e0ad105373b22be3d75ad503fa66a516990354dc Mon Sep 17 00:00:00 2001 From: Phil Pennock Date: Wed, 18 Dec 2019 11:53:11 -0500 Subject: [PATCH 1/2] structured data: Go: handle decode errors The automatic handling of encoding/decoding of structured data can fail, if the data is not in the expected format. For Go, show how this is handled with a connection error handler option. --- developing-with-nats/receiving/structure.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/developing-with-nats/receiving/structure.md b/developing-with-nats/receiving/structure.md index bc75dda..6a7a430 100644 --- a/developing-with-nats/receiving/structure.md +++ b/developing-with-nats/receiving/structure.md @@ -7,7 +7,10 @@ For example, to receive JSON you could do: {% tabs %} {% tab title="Go" %} ```go -nc, err := nats.Connect("demo.nats.io") +nc, err := nats.Connect("demo.nats.io", + nats.ErrorHandler(func(nc *nats.Conn, s *nats.Subscription, err error) { + log.Printf("Async error in %q/%q: %v", s.Subject, s.Queue, err) + })) if err != nil { log.Fatal(err) } @@ -28,6 +31,9 @@ wg := sync.WaitGroup{} wg.Add(1) // Subscribe +// Decoding errors will be passed to the function supplied via +// nats.ErrorHandler above, and the callback supplied here will +// not be invoked. if _, err := ec.Subscribe("updates", func(s *stock) { log.Printf("Stock: %s - Price: %v", s.Symbol, s.Price) wg.Done() From 224888c4a33e36798c851899be1be4db37d1b929 Mon Sep 17 00:00:00 2001 From: Phil Pennock Date: Wed, 18 Dec 2019 17:23:51 -0500 Subject: [PATCH 2/2] address feedback re nil s --- developing-with-nats/receiving/structure.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/developing-with-nats/receiving/structure.md b/developing-with-nats/receiving/structure.md index 6a7a430..5be208c 100644 --- a/developing-with-nats/receiving/structure.md +++ b/developing-with-nats/receiving/structure.md @@ -9,7 +9,11 @@ For example, to receive JSON you could do: ```go nc, err := nats.Connect("demo.nats.io", nats.ErrorHandler(func(nc *nats.Conn, s *nats.Subscription, err error) { - log.Printf("Async error in %q/%q: %v", s.Subject, s.Queue, err) + if s != nil { + log.Printf("Async error in %q/%q: %v", s.Subject, s.Queue, err) + } else { + log.Printf("Async error outside subscription: %v", err) + } })) if err != nil { log.Fatal(err)