Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify return value with panic and recover in golang [duplicate]

Tags:

go

I have a problem how to modify return value with panic and recover in golang please help me, thank you!

func foo1() int {

    defer func() {
        if p := recover(); p != nil {
            fmt.Printf("internal error: %v\n", p)
        }
        // how can I do?
    }()

    panic("test error")
    return 10
}
like image 546
Michael Smith Avatar asked Nov 12 '17 15:11

Michael Smith


1 Answers

one way to do it is naming the return value in the func definition

package main

import "fmt"

func foo() (r int) {
    defer func() {
        if p := recover(); p != nil {
            fmt.Printf("internal error: %v\n", p)
            r = 5 // this modify the return value
        }
    }()

    panic("test error")
    return 3
}

func main() {
    fmt.Println(foo()) // this print 5
}
like image 57
Motakjuq Avatar answered Oct 14 '22 06:10

Motakjuq