Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Wrap and Unwrap Exceptions in Go

Exceptions in golang can be wrapped with fmt.Errorf method. Wrapping is always useful when method needs to propagate exception a nested error received from another method. Most of the times exceptions are wrapped in go, only exclusion where the wrapping is avoided is when user does not want user to know all details about internal error.

package main

import (
    "errors"
    "fmt"
)

func main() {
    _, error := method1()
    fmt.Printf("%+v", error)
}

func method1() (int, error) {
    output, error := nestedMethod()
    wrappedException := fmt.Errorf("wrapping exception [%w]", error)
    return output, wrappedException
}

func nestedMethod() (int, error) {
    return 2, errors.New("nested exception")
}