MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / Example

Function Example

pkg/errors/errors_test.go:31–64  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

29)
30
31func Example() {
32 errApplicationNotFound := errors.DefineNotFound(
33 "application_not_found",
34 "Application with ID `{id}` not found",
35 // Public attribute "id" is parsed from the message format.
36 )
37 errCouldNotCreateDevice := errors.Define(
38 "could_not_create_device",
39 "Could not create Device",
40 "right_answer", // right_answer could be some extra attribute (that isn't rendered in the message format)
41 )
42
43 findApplication := func(id *ttnpb.ApplicationIdentifiers) (*ttnpb.Application, error) {
44 // try really hard, but fail
45 return nil, errApplicationNotFound.WithAttributes("id", id.GetApplicationId())
46 }
47
48 createDevice := func(dev *ttnpb.EndDevice) error {
49 app, err := findApplication(dev.Ids.ApplicationIds)
50 if err != nil {
51 return err // you can just pass errors up
52 }
53 // create device
54 _ = app
55 return nil
56 }
57
58 if err := createDevice(&ttnpb.EndDevice{Ids: &ttnpb.EndDeviceIdentifiers{}}); err != nil {
59 fmt.Println(errCouldNotCreateDevice.WithCause(err).WithAttributes("right_answer", 42))
60 }
61
62 // Output:
63 // error:pkg/errors_test:could_not_create_device (Could not create Device)
64}
65
66func TestFields(t *testing.T) {
67 t.Parallel()

Callers

nothing calls this directly

Calls 5

DefineNotFoundFunction · 0.92
DefineFunction · 0.92
GetApplicationIdMethod · 0.80
WithAttributesMethod · 0.45
WithCauseMethod · 0.45

Tested by

no test coverage detected