droe9376 2018-07-03 10:12 采纳率: 0%
浏览 217
已采纳

在golang中捕获“绑定:地址已在使用中”

I want to catch "bind: address already in use" error in golang.

conn, err := net.ListenUDP("udp", addr)
if err != nil {
    if CATCH_BIND_ERROR(err) {
         // Do something if 'addr' is already in use
    } else {
         panic(err)
    }
}

Is there any way to implement CATCH_BIND_ERROR function?

  • 写回答

2条回答 默认 最新

  • drqja5919276 2018-07-03 10:44
    关注

    The easy way is just to check the text of the error:

    conn, err := net.ListenUDP("udp", addr)
    if err != nil && err.Error() == "bind: address already in use" {
        // Failed to bind, do something
    }
    if err != nil {
        // Some other error
        panic(err)
    }
    

    For a simple case like this, this may be sufficient. This approach is somewhat fragile, however:

    1. If the library ever changes the error message (this does happen from time to time, although is probably unlikely in this specific instance), the check will break
    2. If you do this check in some wrapping function, that may also return other types of errors, you may, at least in theory, receive a false positive, if some other functionality returns an error with the same text (also probably unlikely in this case)

    To mitigate these concerns, you may be able to check for the specific error type, rather than just a textual representation. In your example, the net package provides a few custom errors. The ListenUDP method returns a net.OpError, which means you can examine it more closely. For example:

    conn, err := net.ListenUDP("udp", addr)
    if opErr, ok := err.(*net.OpError); ok {
        if opErr.Op == "listen" && strings.Contains(opErr.Error.Error(), "address already in use") {
            // Failed to bind, do something
        }
    }
    if err != nil {
        // Some other error, panic
        panic(err)
    }
    

    In this case, we still depend on a textual check, so there's still a risk of future library changes breaking the test. But by checking for the net.OpError type, we do mitigate the second risk, that some other error, with the same text, may be raised.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格