Recover, Panic and Defer

Handle fatal errors catching the panic. Get recover error, stack trace or both in a standard error.

Recover

Recover(*error)*Recovery

Get recover error and stack trace to an error pointer. If there are handlers, it run them.

package main

import (
  "fmt"
  "log"
  "github.com/oxequa/grace"
)

func main() {
  err := func() (e error) {
    defer grace.Recover(&e)
    numbers := []int{1, 2}
    fmt.Println(numbers[3]) // panic out of range
    return
  }()
  fmt.Println(err)
  // print error message and stack trace
  err = func() (e error) {
    // add an error handler
    e = grace.Handler(e).Add(func(e error) error {
	    log.Println(e)
	    return e
    })
    defer grace.Recover(&e) // save error and run handlers
    numbers := []int{1, 2}
    fmt.Println(numbers[3]) // panic out of range
    return
  }()
  fmt.Println(err)
  // print error message and stack trace
  fmt.Println("End")
}

Error

(*Recovery)Error()

Get only the error value without stack trace.

package main

import (
  "fmt"
  "github.com/oxequa/grace"
)

func main() {
  err := func() (e error) {
    defer grace.Recover(&e).Error()
    numbers := []int{1, 2}
    fmt.Println(numbers[3]) // panic out of range
    return
  }()
  fmt.Println(err)
  // print only error message
  fmt.Println("End")
}

Stack

(*Recovery)Stack()

Get only the stack trace without error.

package main

import (
  "fmt"
  "github.com/oxequa/grace"
)

func main() {
  err := func() (e error) {
    defer grace.Recover(&e).Stack()
    numbers := []int{1, 2}
    fmt.Println(numbers[3]) // panic out of range
    return
  }()
  fmt.Println(err)
  // print only stack trace
  fmt.Println("End")
}