实现说明
全部逻辑都在函数 classify、main中。
defer 把清理钉在函数边界上,而不是散落在函数体里。
使用要点
- 每一步打印都带着自己的标签:
cancel ->、deadline ->、healthy ->。 - 运行整个文件:
main会依次驱动classify。
常见问题
运行「用 errors.Is 分类 context 错误」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 cancel ->、deadline ->、healthy -> 标签标明各步骤。
签名一览:func classify(err error) string
核心语句
func classify(err error) string {
switch {
case errors.Is(err, context.Canceled):
return "caller gave up"
case errors.Is(err, context.DeadlineExceeded):
return "deadline ran out"
case err == nil:
return "no error"
default:
return "unexpected: " + err.Error()
}
}
expired, expire := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
cancelled, cancel := context.WithCancel(context.Background())
代码示例
package main
import (
"context"
"errors"
"fmt"
"time"
)
func classify(err error) string {
switch {
case errors.Is(err, context.Canceled):
return "caller gave up"
case errors.Is(err, context.DeadlineExceeded):
return "deadline ran out"
case err == nil:
return "no error"
default:
return "unexpected: " + err.Error()
}
}
func main() {
cancelled, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately to force the canceled branch
// a deadline already in the past finishes the context at once
expired, expire := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer expire()
fmt.Println("cancel ->", classify(cancelled.Err()))
fmt.Println("deadline ->", classify(expired.Err()))
fmt.Println("healthy ->", classify(context.Background().Err()))
}