获取返回函数的行号 [英] Get line number on which function returned

查看:118
本文介绍了获取返回函数的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得函数从调用范围返回的行号?

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

示例:

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?

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

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.

推荐答案

AFAIK,不可能自动获取行

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))
}

游乐场

输出:

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>

这篇关于获取返回函数的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆