MST

星途 面试题库

面试题:Go中select语句超时控制下的错误处理优化

现有一个函数,它通过select语句进行网络请求并设置了超时。如果请求超时,除了返回超时错误,还希望能记录此次超时的相关信息(如时间戳)以便后续分析。请对以下代码进行改进实现该需求。代码如下: ```go package main import ( "fmt" "time" ) func networkRequest(ch chan string) { // 模拟网络请求 time.Sleep(3 * time.Second) ch <- "response" } func main() { ch := make(chan string) go networkRequest(ch) select { case res := <-ch: fmt.Println("Received: ", res) case <-time.After(2 * time.Second): fmt.Println("Timeout") } } ```
49.4万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "time"
)

func networkRequest(ch chan string) {
    // 模拟网络请求
    time.Sleep(3 * time.Second)
    ch <- "response"
}

func main() {
    ch := make(chan string)
    go networkRequest(ch)
    var timeoutTime time.Time
    select {
    case res := <-ch:
        fmt.Println("Received: ", res)
    case <-time.After(2 * time.Second):
        timeoutTime = time.Now()
        fmt.Printf("Timeout at %v\n", timeoutTime)
        // 这里可以将超时时间等信息记录到日志文件或者数据库等进行后续分析
    }
}