Golang / GoLang Basics Interview Questions
How does Go handle errors, and what is the difference between %v and %w in fmt.Errorf?
Go treats errors as values returned by functions, not as exceptions thrown from the call stack. This makes error handling explicit and visible. Every function that can fail returns an error as its last return value. The caller is responsible for handling it.
// error is a built-in interface: type error interface { Error() string } // Standard pattern func parseAge(s string) (int, error) { age, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("parseAge: %w", err) // %w wraps the error } if age < 0 || age > 150 { return 0, fmt.Errorf("parseAge: invalid age %d", age) // %v or plain } return age, nil } // Sentinel errors â compare with errors.Is() var ErrNotFound = errors.New("not found") // %w wraps the error â errors.Is / errors.As can inspect the chain wrapped := fmt.Errorf("lookupUser: %w", ErrNotFound) fmt.Println(errors.Is(wrapped, ErrNotFound)) // true // %v formats as string â errors.Is CANNOT find original error notWrapped := fmt.Errorf("lookupUser: %v", ErrNotFound) fmt.Println(errors.Is(notWrapped, ErrNotFound)) // false! // Custom error type type ValidationError struct{ Field, Msg string } func (e *ValidationError) Error() string { return fmt.Sprintf("%s: %s", e.Field, e.Msg) } // errors.As â extract a specific error type from the chain var ve *ValidationError if errors.As(err, &ve) { fmt.Println("bad field:", ve.Field) }
More Related questions...