Add custom error Handler

Add custom handlers to an error. These handlers can be used to do additional operations with errors (print, transform and so on).

Handler

Handler(error)*Handlers

Return an handler interface to manage handlers.

Get

Return a list of error handlers.

(*Handlers)Get()[]HandlerFunc

Add

Add an additional handlers.

(*Handlers)Add(f ...HandlerFunc)error

Add an handler to an existing error.

package main

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

func main() {
  func() (e error) {
    // add an error handler
    e = grace.Handler(e).Add(func(e error) error {
      log.Println(e) // print error
      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("End")
}

Loop

Loop and exec a list of handlers

(*Handlers)Loop()error

Exec custom handler with loop. It also works with multiple error.

package main

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

func main() {
  init := grace.New("test")
  err := grace.Handler(init).Add(func(e error) error {
    e = grace.Prefix(e,"prefix")  // print error
    return e
  },func(e error) error {
    log.Println(e) // print error
    return e
  })
  grace.Handler(err).Loop()
  // test
  // prefixtest
  fmt.Println("End")
}