Quick actions

cmd+k|ctrl+k

Navigation

Languages

Panic and recover / Recovering from panic / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:41:48Z

Updated

2019-03-26T09:41:48Z

package main

import (
	"fmt"
	"runtime"
)

type Foo struct {
	Is []int
}

func (fp *Foo) Panic() (err error) {
	defer PanicRecovery(&err)
	fp.Is[0] = 5
	return nil
}

func PanicRecovery(err *error) {

	if r := recover(); r != nil {
		if _, ok := r.(runtime.Error); ok {
			//fmt.Println("Panicing")
			//panic(r)
			*err = r.(error)
		} else {
			*err = r.(error)
		}
	}
}

func main() {
	fp := &Foo{}
	if err := fp.Panic(); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
	fmt.Println("ok")
}
INFO