github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/util/context.go (about)

     1  package util
     2  
     3  import (
     4  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     5  )
     6  
     7  // privateChanType protects the channel. Since this is a package-private type,
     8  // only methods defined in this package can get the error value from the
     9  // context.
    10  type privateChanType chan error
    11  
    12  const errLogKey = "the key used to extract the error log from the context"
    13  
    14  // ContextWithErrorLog returns a copy of parent and an error channel that can
    15  // be used to receive errors sent with the LogError method.
    16  func ContextWithErrorLog(parent context.Context) (context.Context, <-chan error) {
    17  	errs := make(privateChanType)
    18  	ctx := context.WithValue(parent, errLogKey, errs)
    19  	return ctx, errs
    20  }
    21  
    22  // LogError logs the error to the owner of the context.
    23  //
    24  // If this context was created with ContextWithErrorLog, then this method
    25  // passes the error to context creator over an unbuffered channel.
    26  //
    27  // If this context was created by other means, this method is a no-op.
    28  func LogError(ctx context.Context, err error) {
    29  	v := ctx.Value(errLogKey)
    30  	errs, ok := v.(privateChanType)
    31  	if !ok {
    32  		return
    33  	}
    34  	errs <- err
    35  }