Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Wrap error returned from run with context error #1217

Open
wants to merge 3 commits into
base: v2-exp
Choose a base branch
from

Conversation

goodevilgenius
Copy link

@goodevilgenius goodevilgenius commented Oct 30, 2024

Fixes #1212

Previous PR: #1215

This change depends on features added in go 1.20, therefore the minimum version is bumped to that.;

This allows the error returned by p.Run to be checked for a context error.

For example, given this code:

ctx := context.WithTimeout(context.Background, time.Second*5)
p := tea.NewProgram(model, tea.WithContext(ctx))
_, err := p.Run()
if errors.Is(err, context.DeadlineExceeded) {
  // Handle timeout
}

This change now allows this to work.

This opens up more possibilities, allowing a program to cancel a context, and look for the reason for the cancellation.

Using context.Cause to get the error further allows for even more precise handling, when a context is built with context.WithCancelCause, for example:

ctx, cancel := context.WithCancelCause(context.Background())
ctx = context.WithTimeout(ctx, time.Second*5)
badThing := errors.New("a bad thing happened")

p := tea.NewProgram(model, tea.WithContext(ctx))
go func() {
  // do some stuff
  if badThingHappened {
    cancel(badThing)
  }
)()

_, err := p.Run()
switch {
case errors.Is(err, context.DeadlineExceeded):
  // Handle timeout
case errors.Is(err, badThing):
  // Handle bad thing
case err != nil:
  // Handle other errors
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant