gpt4 book ai didi

go - 如何检查错误是否为 "deadline exceeded"错误?

转载 作者:IT王子 更新时间:2023-10-29 01:34:20 29 4
gpt4 key购买 nike

我正在发送一个带有指定 10 秒超时的上下文的请求:

ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
_, err := client.SendRequest(ctx)
if err != nil {
return 0, err
}

现在,当我遇到超时时,错误消息令人困惑:

context deadline exceeded

是否可以检查 err 是否为超时错误,以便打印更好的错误消息?

ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
_, err := client.SendRequest(ctx)
if err != nil {
if isTimeoutError(err) {
return nil, fmt.Errorf("the request is timeout after 10 seconds")
}
return nil, err
}

如何实现这样的isTimeoutError函数?

最佳答案

在 Go 1.13+ 中最简洁的方法是使用新的 errors.Is功能。

// Create a context with a very short timeout
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()

// Create the request with it
r, _ := http.NewRequest("GET", "http://example.com", nil)
r = r.WithContext(ctx)

// Do it, it will fail because the request will take longer than 1ms
_, err := http.DefaultClient.Do(r)
log.Println(err) // Get http://example.com: context deadline exceeded

// This prints false, because the http client wraps the context.DeadlineExceeded
// error into another one with extra information.
log.Println(err == context.DeadlineExceeded)

// This prints true, because errors.Is checks all the errors in the wrap chain,
// and returns true if any of them matches.
log.Println(errors.Is(err, context.DeadlineExceeded))

关于go - 如何检查错误是否为 "deadline exceeded"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086405/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com