2013-07-09 54 views
5

是否可以获取从调用范围返回函数的行号?获取返回函数的行号

例子:

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

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

我认为这是不可能的,因为它应该从栈中已被删除,但也许它仍然缓存的地方?

用例是我有一个HTTP处理程序,我想记录返回错误的行和文件名,而不必乱丢代码。

回答

7

AFAIK,不可能自动获取执行最后一次退货的行。

然而,用小帮手可以有:

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


输出:

/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> 
+1

+1我只是写了一些类似的代码,并即将发布它作为答案,只是看到不再有任何需要。 –

+0

是的,我已经考虑过包装功能选项。如果看起来没有更好的选择,那么会使用它。 –