Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

go - Best practice to handle error from multiple abstract level

I wondering what is the best way to handle error form multiple level abstraction in go. Every time if I must add a new level abstraction to program, I am forced to transfer error code from level less to level high. Thereby is duplicate communitaces in log file or I must remmember to delete communicate form level low and transfer him to level higher. Below simply example. I skipped creating each object to more shortly and celar code, but I think You understand my problem

type ObjectOne struct{
    someValue int
}

func (o* ObjectOne)CheckValue()error{
    if o.someValue == 0 {
        SomeLogger.Printf("Value is 0 error program") // communicate form first level abstraction to logger
        return errors.New("Internal value in object is 0")
    }
    return nil
}

type ObjectTwoHigherLevel struct{
    objectOne ObjectOne
}

func (oT*  ObjectTwoHigherLevel)CheckObjectOneIsReady() error{
    if err := oT.objectOne.CheckValue() ; err != nil{
        SomeLogger.Printf("Value in objectOne is not correct for objectTwo %s" , err) //  second communicate
        return  err
    }
    return nil
}

type ObjectThreeHiggerLevel struct{
    oT ObjectTwoHigherLevel
}

func (oTh* ObjectThreeHiggerLevel)CheckObjectTwoIsReady()error{
    if err := oTh.oT.CheckObjectOneIsReady() ; err != nil{
        SomeLogger.Printf("Value in objectTwo is not correct for objectThree %s" , err)
    return err
    }
    return nil
}

In result in log file I get duplicate posts

Value is 0 error program 
Value in objectOne is not correct for objectTwo Internal value in object is 0 
Value in objectTwo is not correct for objectThree Internal value in object is 0

In turn if I only transfer some err to higher level without additional log I lost information what happend in each level.

How this solve ? How privent duplicate communicates ? Or My way is the good and the only ?

Problem is more frustrating if I create a few object which search something in database on a few abstraction level then I get also few lines form this same task in logFile.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...