Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Regarding error context: I'd advocate simple error-chaining using a linked list. If a function fails, it returns an error wrapping the underlying error as the cause, and so on up the stack. The top of the stack can inspect or print the error chain ("A failed because B failed because ..."), or pinpoint the error that was the root cause.

I would love for Go to include something like this:

    type Error struct {
        Description string
        Cause       error
    }
    
    func NewError(cause error, descriptionFmt string, args ...interface{}) error {
        return Error{
            Description: fmt.Sprintf(descriptionFmt, args...),
            Cause:       cause,
        }
    }
    
    func (me Error) Error() string {
        if me.Cause == nil {
            return me.Description
        }
        return fmt.Sprintf("%v: %v", me.Description, me.Cause.Error())
    }
    
    func RootCause(err error) error {
        if err, ok := err.(Error); ok && err.Cause != nil {
            return RootCause(err.Cause)
        }
        return err
    }



Great library.


or gopkg.in/errgo.v1 which is a bit more opinionated about error causes.


Many Go error libraries exist mostly to provide this kind of functionality.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: