RaditzLawliet
RaditzLawliet

Reputation: 503

Is it possible to get the source code line which return value returned?

When building web apps using gin/echo/mux or else, I have some handler or func with many possibility of returning error. Because of the complexity of current application, My idea is to create some post-middleware or handler and get which source code returned value come from and logging them, it is possible?

func main (){
    // is it possible to get which line returned value, i.e line 11 of main.go?
    e := Validate(10)
    if e != nil {
        fmt.Println("Error: %v", e)
    ]
}

func Validate(i int) error {
    if i >= 10 {
        return fmt.Errorf("want less ten, got %v", i) // i.e line 11
    } else if i < 0 {
        return fmt.Errorf("negative number: %v", i)
    }
    return nil
}

Upvotes: 0

Views: 155

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79684

Your approach is backwards. Don't try to figure this out from the caller--instead have the function itself include a stack trace in the error. github.com/pkg/errors can help here.

As an example:

import "github.com/pkg/errors"

func main (){
    e := Validate(10)
    if e != nil {
        fmt.Println("Error: %v", e)
    ]
}

func Validate(i int) error {
    if i >= 10 {
        return errors.Errorf("want less ten, got %v", i) // i.e line 11
    }
    if i < 0 {
        return errors.Errorf("negative number: %v", i)
    }
    return nil
}

Upvotes: 1

Related Questions