-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors_data-context.go
More file actions
37 lines (30 loc) · 869 Bytes
/
errors_data-context.go
File metadata and controls
37 lines (30 loc) · 869 Bytes
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
// Copyright (c) 2023 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
"context"
)
type dataCtxKeyType string
const dataCtxKey dataCtxKeyType = "data"
func AddContextDataToError(ctx context.Context, err error) error {
return AddDataToError(err, DataFromContext(ctx))
}
func AddToContext(ctx context.Context, key string, value any) context.Context {
newData := map[string]any{key: value}
if v := ctx.Value(dataCtxKey); v != nil {
if data, ok := v.(map[string]any); ok {
for k, v := range data {
newData[k] = v
}
}
}
return context.WithValue(ctx, dataCtxKey, newData)
}
func DataFromContext(ctx context.Context) map[string]any {
value := ctx.Value(dataCtxKey)
if value == nil {
return nil
}
return value.(map[string]any)
}