有没有办法在异常处理开关中按类型匹配 golang 上下文超时错误?switch err.(type)case context.deadlineExceededError: fmt.Println("deadline exceeded")}不会编译,由于cannot refer to unexported name context.deadlineExceededErrorAFAICS 由于类型未导出,因此只能通过字符串比较来处理。package mainimport ( "context" "fmt" "time")const shortDuration = 1 * time.Secondfunc main() { ctx, cancel := context.WithTimeout(context.Background(), shortDuration) defer cancel() select { case <-time.After(shortDuration*2): fmt.Println("overslept") case <-ctx.Done(): err := ctx.Err() switch err.(type) { case context.deadlineExceededError: fmt.Println("deadline") } fmt.Printf("error %T: %v\n", err, err) }}$ go build main.go# command-line-arguments./main.go:21:8: cannot refer to unexported name context.deadlineExceededErrorvs 字符串比较 case <-ctx.Done(): err := ctx.Err() errType := fmt.Sprintf("%T",err) switch errType { case "context.deadlineExceededError": fmt.Println("deadline") } fmt.Printf("error %T: %v\n", err, err) }$ go build main.go && ./maindeadlineerror context.deadlineExceededError: context deadline exceeded
- 1 回答
- 0 关注
- 702 浏览
添加回答
举报
0/150
提交
取消