0

My function must return a string whatever success or panic.

func getDBStoreStatus() string{
    var replyMessage string
    defer func() string{ 
        if err := recover(); err != nil {  
            replyMessage = "Error happend." 
        }
    return replyMessage
    }()

    //do something to store row into DB
    db, err := sql.Open("mysql", "user1:password@/databaseName?charset=utf8") 
    newMessage, err := db.Prepare("INSERT .............
    res, err := newMessage.Exec(...........
    if err != nil { 
        panic(err)
    }
    replyMessage = "OK"
    return replyMessage
}

How can I return a string, if the panic processed by defer section? You can see the return statement in defer section doesn't work properly.

Yi Jiang
  • 3,938
  • 6
  • 30
  • 62

1 Answers1

1

Name your return parameter, then you can set it in the defer method:

func getDBStoreStatus() (replyMessage string) {
    defer func(){ 
        if err := recover(); err != nil {  
            replyMessage = "Error happend." 
        }
    }()

    //do something to store row into DB
    db, err := sql.Open("mysql", "user1:password@/databaseName?charset=utf8") 
    newMessage, err := db.Prepare("INSERT .............
    res, err := newMessage.Exec(...........
    if err != nil { 
        panic(err)
    }
    replyMessage = "OK"
    return replyMessage
}

See the Go Blog post on Defer, Panic and Recover:

  1. Deferred functions may read and assign to the returning function's named return values.

    In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:

    func c() (i int) {
        defer func() { i++ }()
        return 1
    }
    

I don't really see the point, though. You could just do:

    if err != nil { 
        return "Error happend."
    }

instead of panic(err).

muru
  • 4,723
  • 1
  • 34
  • 78
  • The question just is an abstraction of my reality problem. I need do many other things to handle multiple errors. Your solution works! Thank you! – Yi Jiang Feb 25 '16 at 04:12