我得到了一段如下代码:
if timeoutErr, ok := err.(net.Error); ok && timeoutErr.Timeout() {
// Some code that need to test
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能生成一个与这里的条件匹配的错误,以便代码将流经 if.
Error是一个接口:
type Error interface {
error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}
Run Code Online (Sandbox Code Playgroud)
要实现它,您需要执行类似的操作(未经测试):
type MyError struct {
error
}
func (e MyError) Timeout() bool {
return true
}
func (e MyError) Temporary() bool {
return true
}
func (e MyError) Error() string {
return ""
}
Run Code Online (Sandbox Code Playgroud)
请注意,您也必须实现,Error()因为Errorembeds error。
| 归档时间: |
|
| 查看次数: |
2498 次 |
| 最近记录: |