dqz84361326 2013-07-09 08:32 采纳率: 0%
浏览 49
已采纳

获取返回函数的行号

Is it possible to get the line number on which a function returned from the calling scope?

Example:

func callee() error {
  if cond {
    return errors.New("whoops!")
  }
  return nil
}

func caller() {
  // Possible to retrieve the line number of callee return here?
  callee()
}

I assume that's not possible, since it should be already removed from the stack, but maybe it's still cached somewhere?

The use case is that I have a HTTP handler and I'd like to log the line and filename on which the error was returned, without having to litter the code.

  • 写回答

1条回答 默认 最新

  • dravpuso44681 2013-07-09 08:38
    关注

    AFAIK, it is not possible to automatically acquire the line where the last return was executed.

    However, with a small helper one can have:

    package main
    
    import (
            "fmt"
            "runtime"
    )
    
    func here(s string, args ...interface{}) error {
            _, fname, fline, _ := runtime.Caller(1)
            h := fmt.Sprintf("%s:%d: ", fname, fline)
            return fmt.Errorf(h+s, args...)
    }
    
    func foo(i int) error {
            if i == 2 {
                    return here("cannot handle %d", i) // line 16
            }
    
            if i%3 == 0 {
                    return here("also cannot handle %d", i) // line 20
            }
    
            return nil
    }
    
    func main() {
            fmt.Println(foo(2))
            fmt.Println(foo(3))
            fmt.Println(foo(4))
    }
    

    Playground


    Output:

    /tmpfs/gosandbox-92c2a0f2_32bdf9d9_3c7d2a0a_80ba8510_f68d9721/prog.go:16: cannot handle 2
    /tmpfs/gosandbox-92c2a0f2_32bdf9d9_3c7d2a0a_80ba8510_f68d9721/prog.go:20: also cannot handle 3
    <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)