ARTICLE AD BOX
I am reading up about wrapping and unwrapping errors when doing a chain of calls. On this topic I came up the following snippet of code.
err := controller() stack := []error{err} for len(stack) > 0 { e := stack[len(stack)-1] stack = stack[:len(stack)-1] if e == nil { continue } fmt.Println("Error part:", e) switch u := any(e).(type) { case interface{ Unwrap() error }: stack = append(stack, u.Unwrap()) case interface{ Unwrap() []error }: stack = append(stack, u.Unwrap()...) } }The first part of the program is omitted but the first line results in a chain of errors once the function "controller()" is called. The subsequent loop then prints all the errors contained , first the latest one up until the first in the chain (deepest down). I am puzzeled what exactly happens in the switch statement code. I understand that 'u' can basically be assigned the type of anything ? (the any clause?) but what happens in the first case block ? (the one always chosen in this case when I debugged it).
Is it that when you invoke Unwrap() on "u" and the result implements the 'error' interrface this path (case) is selected? or is this a misinterpretation? Further questions:
What would trigger the second case statement which seems to check for a slice of error? When would this happen
What would happen if I feed it a non error (interface) type which doesnt even have an Unwrap() function? Would it crash or just do nothing since both cases of the switch wont be valid
Thanks Peter
