如何准确标记错误以符合golang

I have seem this answer and use @OneOfOne answers. How do you get a Golang program to print the line number of the error it just called?

But there is some questions.

func FancyHandleError(err error) (b bool) {
    if err != nil {
        pc, fn, line, _ := runtime.Caller(1)
        log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), fn, line, err)
        b = true
    }
    return
}

func main(){
    FancyHandleError(funcA())
}

func funcA()error{
    err := funcB()
    return err
}

func funcB()error{
    err := funcC()
    return err
}

func funcC()error{
    err := errors.New("deep errors!!") //I want to get the location in here!!!!!!!!!!!!!!!!!!!!!!
    return err
}

It will print "[error] in main.main[/root/temp/error.go:23]" That is in function main's line number.

But how to locate the error's line number in function C()?

See runtime.Caller which will give you all the details you need.

Your custom NewError function may look like this:

func NewError(message string) error {
    _, file, line, _ := runtime.Caller(1)
    return fmt.Errorf("[%s][%d] : %s" , file, line, message)
}

Here is play link for a sample play

If you're using the log package, you can instruct the logger to prefix the entries with various information.

log.SetFlags(log.Lshortfile)