douye4051 2017-09-08 10:25
浏览 73
已采纳

尝试异常替代方案以保护应用程序不崩溃

I have a Go application for scrape URLs. The problem is it sometimes crashes and returns this error:

panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.dom6(0x187d4140, 0x8, 0x187d4179, 0x5, 0x187c0800, 0x6, 0x13, 0x83007cb)
        /root/sswork.go:326 +0x6b
main.sub(0x187d4140, 0x8, 0x84464e0, 0x6, 0x6, 0x187d4140, 0x8, 0x187d4179, 0x5, 0x187c0800, ...)
        /root/sswork.go:298 +0xb3
main.main()
        /root/sswork.go:615 +0xccb

on line 298 is this function :

294: // try our list of substitutions, if one works return it
295: func sub(str string, xs []subs, u string, p string, h string) string {
296:    for _, x := range xs {
297:        if strings.Contains(str, x.pattern) {
298:            return strings.Replace(str, x.pattern, x.fn(u, p, h), 1)
299:        }
300:    }
301:    return str
302:}

How can I solve my problem so it doesn't crash the application any more?

324: // the first 6 characters of the above
325: func dom6(u string, p string, d string) string {
326:    return domfull(u, p, d)[0:6]
327: }
  • 写回答

1条回答 默认 最新

  • douwen4125 2017-09-08 10:55
    关注

    The error is at line 326, not 298. And to avoid such panics, perform manual index check before attempting to index or slice a slice, array or string.

    You indicated that the code at line 298 is:

    // the first 6 characters of the above
    func dom6(u string, p string, d string) string {
        return domfull(u, p, d)[0:6]
    }
    

    Check the length of the string returned by domfull() before attempting to slice it, e.g.:

    func dom6(u string, p string, d string) string {
        df := domfull(u, p, d)
        if len(df) < 6 {
            return df
        }
        return df[:6]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)