jackc/pgx · error · ConnectError

AfterConnect error

Error message

AfterConnect error: %w

What it means

The connection was successfully established but the user-supplied AfterConnect hook returned an error. The connection is closed and the hook's error is wrapped and surfaced inside a ConnectError.

Solutions

  1. Inspect the wrapped error from your AfterConnect callback
  2. Add logging inside the hook to find the failing statement
  3. Ensure the hook's SQL is valid for the target database
  4. Check the hook does not assume a specific server version
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at pgconn/pgconn.go:171 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/32e1630a34b27109. Report an issue: GitHub.

Appendix: source

Thrown at pgconn/pgconn.go:171

	if len(errs) > 0 {
		allErrors = append(allErrors, errs...)
	}

	if len(connectConfigs) == 0 {
		return nil, &ConnectError{Config: config, err: fmt.Errorf("hostname resolving error: %w", errors.Join(allErrors...))}
	}

	pgConn, errs := connectPreferred(ctx, config, connectConfigs)
	if len(errs) > 0 {
		allErrors = append(allErrors, errs...)
		return nil, &ConnectError{Config: config, err: errors.Join(allErrors...)}
	}

	if config.AfterConnect != nil {
		err := config.AfterConnect(ctx, pgConn)
		if err != nil {
			pgConn.conn.Close()
			return nil, &ConnectError{Config: config, err: fmt.Errorf("AfterConnect error: %w", err)}
		}
	}

	return pgConn, nil
}

// buildConnectOneConfigs resolves hostnames and builds a list of connectOneConfigs to try connecting to. It returns a
// slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain
// values if some hosts were successfully resolved and others were not.
func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) {
	// Simplify usage by treating primary config and fallbacks the same.
	fallbackConfigs := []*FallbackConfig{
		{
			Host:      config.Host,
			Port:      config.Port,
			TLSConfig: config.TLSConfig,
		},
	}

View on GitHub (pinned to ec1a0befd2)