英文:
Correctly handle context.deadlineExceededError in golang
问题
在异常处理的switch语句中,有没有一种方法可以通过类型匹配golang的context deadline exceeded错误?
switch err.(type)
case context.deadlineExceededError:
fmt.Println("deadline exceeded")
}
由于无法引用未导出的名称context.deadlineExceededError,这段代码无法编译通过。
cannot refer to unexported name context.deadlineExceededError
根据我所看到的情况,由于该类型未导出,只能通过字符串比较来处理。
package main
import (
"context"
"fmt"
"time"
)
const shortDuration = 1 * time.Second
func 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.deadlineExceededError
与字符串比较相比:
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 && ./main
deadline
error context.deadlineExceededError: context deadline exceeded
英文:
Is there a way to match a golang context deadline exceeded error by type in an exception handling switch?
switch err.(type)
case context.deadlineExceededError:
fmt.Println("deadline exceeded")
}
won't compile, due to
cannot refer to unexported name context.deadlineExceededError
AFAICS since the type isn't exported, it can only be handled by string comparison.
package main
import (
"context"
"fmt"
"time"
)
const shortDuration = 1 * time.Second
func 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.deadlineExceededError
vs string comparison
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 && ./main
deadline
error context.deadlineExceededError: context deadline exceeded
答案1
得分: 2
你可以使用context.DeadlineExceeded
值(文档):
- 可以直接使用
err == context.DeadlineExceeded
进行比较, - 或者使用
errors.Is(err, context.DeadlineExceeded)
。
英文:
You can use the context.DeadlineExceeded
value (documentation):
- either for direct
err == context.DeadlineExceeded
comparison, - or using
errors.Is(err, context.DeadlineExceeded)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论