Standard library / context

context.WithCancelCause()

Create a cancelable context that records an error cause. Err remains Canceled; Cause exposes the recorded error. Expected stdout: 'context canceled stopped\n'.

Formal Syntax & Structure

go syntaxgo
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)

Parameters & Attributes

NameTypeDescription
parentContextNon-nil parent context.

Return Value

(ctx Context, cancel CancelCauseFunc)

Derived context and cause-setting cancel function.

Working Example

Example Snippetgo
package main
import (  "context"  "errors"  "fmt")
func main() {  ctx, cancel := context.WithCancelCause(context.Background())  defer cancel(nil)  cancel(errors.New("stopped"))  fmt.Println(ctx.Err(), context.Cause(ctx))}
Go Reference