go: proposal: os/signal: Provide a new error type to communicate the signal triggered context cancellation
This comes from the need to fix #60733.
In order to provide the information of which signal triggered context cancellation in signal.NotifyContext using context.Cause, we need a new error type (as that’s the only type allowed by context cause) to communicate that info back to the user.
The proposal is to define it as a simple struct that can only be used by pointer as an error:
// CanceledBySignalError represents the error can be retrieved via context.Cause
// on the context returned by NotifyContext to inspect which signal caused the
// cancellation.
type CanceledBySignalError struct {
// The signal caused the context cancellation.
Signal os.Signal
}
func (cse *CanceledBySignalError) Error() string {
return fmt.Sprintf("context canceled by signal %v", cse.Signal)
}
So users can inspect the signal via code like:
select {
case <-ctx.Done():
cause := context.Cause(ctx)
var cse *signal.CanceledBySignalError
if errors.As(cause, &cse) {
sig := cse.Signal
// Do something with sig
}
}
About this issue
- Original URL
- State: open
- Created a year ago
- Reactions: 8
- Comments: 15 (7 by maintainers)
I think this should be named
os.SignalErrorinstead ofsignal.CanceledBySignalError, so that it may be used for cases beyond justsignal.Notify. For example, I could envision a caller transforming anexec.ExitErrorby checking whether itsProcessStateindicates termination by signal and returning aSignalError.Actually,
SignalErrorwould be even more useful ifexec.ExitErrorhad a convenienceIsmethod for it: