![]() Whenever error happens in the middle of (goroutine) process, then we will send that error object through the channel and then stop process immediately from. In the below example, I've prepared a channel called chErr. To achieve that, we need an additional channel to transport the error object from goroutine into main routine. And sometimes, we might need to retrieve that error object on the main routine. There might be a situation where we need to stop the goroutine in the middle of the process because error occurred. simulate a process that takes 4 second to completeĮxample #3 scenario: context canceled by force due to error occurred In this scenario, we make the process takes longer than context timeout, so ideally the <-ctx.Done() will also be executed. whole process is complete")Įxample #2 scenario: context timeout exceeded cancel context by force, assuming the whole process is completeįmt.Println("context cancelled by force. simulate a process that takes 2 second to complete In the test, we'll try to make the context to be canceled before the timeout exceeds, so the <-ctx.Done() will be executed. We can perform some checking on the error object to see whether the context is canceled by force or exceeding the timeout.Ĭontext package provides two error objects, context.DeadlineExceeded and context.Timeout, this two will help us to identify why <-ctx.Done() is called.Įxample #1 scenario: context cancelled by force (via cancel()) ![]() So basically the <-ctx.Done() will be called on two conditions:Īnd when that happens, the ctx.Err() will never be nil. Successive calls to Done return the same value. Done may return nil if this context can never be canceled. ![]() If you want to use the timeout and cancellation feature from the context, then in your case the ctx.Done() need to be handled synchronously.ĭone returns a channel that's closed when work is done on behalf of this context should be canceled. Basically, it won't terminate in 3 seconds so I am trying to understand how can golang's ctx help me with this? What I do not understand is that how do I make my go func myfunc get aborted in 3 seconds using the context logic. I also get the fact that in my myfunc once select matches on the case for default, it won't match on the done. I understand that context times-out after 3 seconds and hence it does give me the expected error when I call ctx.Err() in the end. In main, ctx err is context deadline exceeded I have the above snippet that does print the output like this I was not canceled Fmt.Printf("Ctx is kicking in with error:% v\n", ctx.Err())įmt.Printf("In main, ctx err is % v\n", ctx.Err()) ![]()
0 Comments
Leave a Reply. |