In Go, errors are values returned by functions rather than exceptions thrown by the runtime. You handle them by checking the second return value and using errors.Is or errors.As to inspect specific error types.
func readFile(name string) ([]byte, error) {
data, err := os.ReadFile(name)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("file missing: %w", err)
}
return nil, err
}
return data, nil
}