How to make method return value if panic happen and processed in defer func(){...}() in golang
Tag : go , By : clifton anderson
Date : March 29 2020, 07:55 AM
This might help you My function must return a string whatever success or panic. , 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
}
func c() (i int) {
defer func() { i++ }()
return 1
}
if err != nil {
return "Error happend."
}
|
Go, is it possible to put defer in sub func
Date : March 29 2020, 07:55 AM
help you fix your problem I think I understand what you're asking. You want to know if a function can place a function on the defer stack of the caller. The answer to that is no. One possible solution to this is to have the function that wants to defer something return that function to the caller and have the caller do the defer. For example: func test2() {
r, cleanup := subc()
defer cleanup()
r.Use()
}
func subc() (*Resource, func()) {
r, err := Open("a")
if err != nil {
log.Fatalf("error opening 'a'\n")
}
return r, func() { r.Close() }
}
|
When defer func evaluates its parameters
Tag : go , By : user123585
Date : March 29 2020, 07:55 AM
this one helps. Ok I just figured out. If you pass any parameters to the defer func (like the 2nd defer function above), those parameters are evaluated when the defer function is deferred, not when they are executed. That means in my example err is still nil and has not been assigned to a new error yet. on the other hand, in 1st defer above, err is not a parameter, but a variable in function a, and when 1st defer is executed, it has already been assigned to a new error.
|
Does Azure functions Fan-out / Fan-in func always have better performance than just running a single function thread?
Date : March 29 2020, 07:55 AM
around this issue Obviously, if your activity to be executed multiple times is something lightweight (e.g. adding numbers), it's going to be faster to execute it just within the single Function without remote calls, queues, and leaving the process whatsoever. Fan-out / Fan-in pattern is only valid for expensive computations or IO operations that can benefit from parallelization.
|
defer func not recover
Tag : go , By : Nathan Good
Date : March 29 2020, 07:55 AM
With these it helps A call to recover will only stop a panic when called directly from the deferred function. Here's the relevant text from the recover documentation:
|