go / expert
Snippet
Structured Error Context Extraction via Custom Unwrap Interfaces and errors.As
Go's errors.As traverses error chains recursively via Unwrap() methods. By checking for custom interfaces rather than concrete struct pointer types, callers decouple error inspection logic from concrete implementations while extracting domain-specific metadata.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package mainimport ("errors""fmt")type CodedError interface {errorErrorCode() string}type DomainError struct {Code stringMessage stringErr error}func (e *DomainError) Error() string { return fmt.Sprintf("[%s] %s", e.Code, e.Message) }func (e *DomainError) ErrorCode() string { return e.Code }func (e *DomainError) Unwrap() error { return e.Err }func ExtractCode(err error) string {var coded CodedErrorif errors.As(err, &coded) {return coded.ErrorCode()}return "UNKNOWN_ERROR"}func main() {base := errors.New("connection timeout")wrapped := &DomainError{Code: "NET_504", Message: "Gateway Timeout", Err: base}fmt.Println("Extracted Error Code:", ExtractCode(wrapped))}
Breakdown
1
if errors.As(err, &coded) {
Searches the error unwrapping chain for any error in the tree that satisfies the CodedError interface contract.